Python Reverse String

Strings are basically sequence of characters. Python doesn’t support in-built string functions such as reverse() to reverse a string.

Python Reverse String
Python Reverse String

The following are the ways to reverse a string in Python:

  1. By using a for loop
  2. By using a while loop
  3. By using a Slicing
  4. By using join() method
  5. By using Recursion
  6. By using List reverse() method
  7. By using stack

Method 1: Reverse a string using for loop

 def rev_string_loop(s): res = '' for x in s: res = x + res return res str = 'STRING' print('Reversed String =', rev_string_loop(str)) 

Output:

Reversed String = GNIRTS


Method 2: Reverse a string using while loop

 def rev_string_loop(x): res = '' length = len(x) - 1 while length >= 0: res = res + x[length] length = length - 1 return res str = 'STRING' print('Reversed String =', rev_string_loop(str)) 

Output:

Reversed String = GNIRTS


Method 3: Reverse a string using Slicing

 input="STRING" length=len(input) res=input[length::-1] print (res) 

Output:

GNIRTS


Method 4: Reverse a string using join() method

 input = 'STRING' result=''.join(reversed(input)) print(result) 

Output:

GNIRTS


Method 5: Reverse a string using Recursion

 def rev_string(x): if len(x) == 0: return x else: return rev_string(x[1:]) + x[0] x = "STRING" print ("Original string: ") print (x) print ("Reversed string: ") print (rev_string(x)) 

Output:

Original string:
STRING
Reversed string:
GNIRTS


Method 6: Reverse a string using List reverse() method

 input_list = [1, 2, 3, 4, 5] input_list.reverse() print(input_list) 

Output:

[5, 4, 3, 2, 1]


Method 7: Reverse a string using stack

 def create(): stack1=[] return stack1 def size(stack1): return len(stack1) def isEmpty(stack1): if size(stack1) == 0: return true def push(stack1,element): stack1.append(element) def pop(stack1): if isEmpty(stack1): return return stack1.pop() def rev_string(input): x = len(input) stack1 = create() for i in range(0,x,1): push(stack1,input[i]) input="" for i in range(0,x,1): input+=pop(stack1) return input n = "STRING" print ("Original string: ") print (n) print ("Reversed string: ") print (rev_string(n)) 

Output:

Original string:
STRING
Reversed string:
GNIRTS


References

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 195