Reverse a String in Python1 min read

In this example, I’ll show you How to reverse a string in Python.

To reverse a string entered by the user in python, you have to ask from user to enter the desired string which is going to reverse to reverse that string and print the reversed string as output as shown in the program given below.

Python Programming Code to Reverse a String

Following python program ask from the user to enter a string to reverse that string and print it as output:

This is a Python program that reverses a string entered by the user.

Here’s a brief explanation of how the code works:

  1. The user is prompted to enter a string or to exit the program by entering ‘x’.
  2. If the user enters ‘x’, the program exits.
  3. If the user enters a string, the “revstring” variable is assigned the reversed version of the string using slicing. Slicing is a technique in Python that allows you to extract a sub-string from a string by specifying a range of indices. In this case, the slicing syntax “string[::-1]” extracts the entire string and reverses it by specifying a step size of -1.
  4. The original string and the reversed string are printed to the console.

Here is the sample run of the above python program to illustrate how to reverse a string in python:

Leave a Comment