/  Technology   /  Reverse a string in Python
Reverse a string in Python

Reverse a string in Python

Python doesn’t have any built-in method for a string reversal like a list which has a list method list.reverse(). So, we must manually reverse a string using any of the following methods:

  • Using slicing
  • Using loop
  • Using join

 

1. Using slicing:

Slicing helps in obtaining a substring, sub-tuple, or sublist from any given iterable like a string, tuple, or list respectively.

 

Here we started the slicing process with the length of the string using the len() function and printed all through the elements till the first element with index 0 and given the step value as -1.

 

start: len(string)

stop: empty(means till the element with index 0)

step: -1

 

Example:

string = "Pythonbyi2tutorials"
print("The original string is: ",string)

string_length=len(string)

sub_string=string[string_length::-1]
print("The reversed string is:"+sub_string))

Output:

 

2. Using loop:

Here we create an empty list named rev_string which stores the final reversed string. We now iterate through the string using an iterator named index which is initialized with the len of the string, using a loop. 

In each iteration we concatenate the value of string[index-1] with our empty list rev_string and decrement the value of index. 

 

Example:

string = "i2tutorials"
print("The original string is: ",string)

rev_string=[]

index = len(string)
while index > 0:
    rev_string +=string[ index -1 ]
    index= index - 1
print("The reversed string is:",rev_string))

Output:

 

3. Using reversed() and join:

The built-in function reversed takes a sequence as a parameter and returns an iterator which iterates the given sequence in the reverse order. After we get all the characters we use the join  method to merge all these and store it in rev_string.

 

Example:

string = "i2tutorials"
print("The original string is: ",string)

rev_string=''.join(reversed(string))
print("The reversed string is:",rev_string))

Output:

 

Leave a comment