Python Reverse String

python-reverse-string

How do you reverse a string in Python?

In Python, strings are ordered sequences of character data.

There is no built-in method to reverse a string. However, strings can be reversed in several different ways.

svg viewer

Methods

Three methods to reverse a string are explained below:

1. Slicing

Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0.

To reverse a string using slicing, write:

stringname[stringlength::-1]# method 1 

Or write without specifying the length of the string:

stringname[::-1]# method2

The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

  1. str=”Python” # initial string
  2. stringlength=len(str) # calculate length of the list
  3. slicedString=str[stringlength::-1] # slicing
  4. print (slicedString) # print the reversed string

2. Loop

To start, let’s create a new array called reversedString[].

We can then loop over the list with iterating variable index initialized with the length of the list.

  • In each iteration, concatenate value of str[index-1] with reverseString
  • Decrement the index.

We then simply keep iterating until the index is less than zero.

  1. str = “Python” # initial string
  2. reversedString=[]
  3. index = len(str) # calculate length of string and save in index
  4. while index > 0:
  5.     reversedString += str[ index – 1 ] # save the value of str[index-1] in reverseString
  6.     index = index – 1 # decrement index
  7. print(reversedString) # reversed string

3. Use join

This is an incredible procedure that exploits Python’s iterator convention. This strategy reverses a string utilizing reverse emphasis with the reversed() worked in capacity to push through the components in the string in reverse request and afterward use .join() technique to consolidate the entirety of the characters coming about because of the reversed cycle into another string.

The general syntax is

str="Python"
reversedstring=''.join(reversed(str))

The following Python code demonstrates the concept.

  1. str = ‘Python’ #initial string
  2. reversed=”.join(reversed(str)) # .join() method merges all of the characters resulting from the reversed iteration into a new string
  3. print(reversed) #print the reversed string

More links:

Python tutorial

Zen of Python