How to Reverse a string in Python

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
    1. The function ‘code(s)‘ takes a single argument ‘s‘, which is expected to be a string.
    2. 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.
    3. 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top