/  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

  1. 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. 

  1. 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.

 

Leave a comment