In this tutorial, we will learn how to reverse string in Python
Reverse a String in Python
Code and Explanation :
def code(s): # Function to reverse the string using slicing return s[::-1] # Prompt the user to enter a string str1 = input("Enter a string: ") # Print the original string entered by the user print("Original string:", str1) # Call the 'code' function to reverse the string and store the result result = code(str1) # Print the reversed string print("Reversed string:", result)
Here’s how the code works:
- EXPLATION OF FUNCTION
- The function ‘code(s)‘ takes a single argument ‘s‘, which is expected to be a string.
- Inside the function, the string ‘s‘ is reversed using Python’s slicing technique ‘s[::-1]‘.
- ‘s[::-1]’ works by slicing the string starting from the end (-1 step) to the beginning, effectively reversing it.
- The reversed string is then returned by the function.
- Taking user input as a string and storing in variable ‘str1′.
- Printing the original string.
- Reversing the string by using the function ‘code(s)’ and storing in variable ‘result‘.
- Printing the reversed string.
Sample Output :-
- Enter a string: CodeSpeedy
- Original string: CodeSpeedy
- Reversed string: ydeepSedoC