Change language

Reverse string in Python (5 different ways)

| | |

Using a loop

Output:

 The original string is: Geeksforgeeks The reversed st ring (using loops) is: skeegrofskeeG 

Explanation: In the above code, we call a function that loops the line that iterates over each element and intelligently concatenates each character at the beginning, to get a reversed line.

Using recursion

# Python code to reverse the line
# using a loop

 

def reverse (s):

str = ""

for i in s:

str = i + str

return str

 

s = "Geeksforgeeks"

 

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

print (s)

 

print ( "The reversed string (using loops) is:" , end = "")

print (reverse (s))

# Python code to reverse the string
# using recursion

  

def reverse (s):

if len (s) = = 0 :

  return s

  else :

return reverse (s [ 1 : ]) + s [ 0 ]

 

s = "Geeksforgeeks"

 

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

print (s)

  

print ( " The reversed string (using recursion) is: " , end = " ")

print (reverse (s))

Output:

 The original string is: Geeksforgeeks The reversed string (using recursion) is: skeegrofskeeG 

Explanation: In the above code, a string is passed as an argument to the recursive function to reverse the string. In a function, the basic condition is that if the length of the string is 0, the string is returned. If not 0, the inverse function is called reversely to cut a portion of the string other than the first character and concatenate the first character with the end of the chopped string.

Stack Usage

# Python code to reverse the line
# using the stack

 
# Function for creating an empty stack. This
# initializes the stack size to 0

def createStack ():

stack = []

return stack

 
# Function for determining the stack size

def size (stack):

return len (stack)

  
# The stack is empty if the size is 0

def isEmpty (stack):

  if size (stack) = = 0 :

  return true

  
# Function for adding an item to the stack. This
# increases the size by 1

def push (stack, item):

stack.append (item)

 
# Function to remove an item from the stack.
# Decreases size by 1

def pop (stack) :

if isEmpty (stack) : return

return stack.pop ()

 
# Stack-based function to reverse a string

def reverse (string): 

n = len (string)

 

# Create empty stack

stack = createStack ()

 

# Push all characters in the string onto the stack

for i in range ( 0 , n, 1 ):

  push (stack, string [i])

 

# Make the line empty, since everything

# characters are stored on the stack

string = ""

 

# Pop all line characters and put

# them back to line

for i in range ( 0 , n, 1  ):

string + = pop (stack)

 

return string

 
# Driver code

s = "Geeksforgeeks"

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

print (s)

print ( "The reversed string (using stack) is : " , end = " ")

print (reverse (s))

Output:

 The original string is: Geeksforgeeks The reversed string (using stack) is: skeegrofskeeG 

Explanation: An empty stack was created. One by one, the characters in the string are pushed onto the stack. 
One by one, all characters are popped off the stack and returned to the string.

Using the extended slice syntax

# Python code to reverse the string
# use advanced slice syntax

 
# Function to reverse the string

def reverse (string):

string = string [:: - 1 ]

return string

  

s = "Geeksforgeeks"

 

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

print (s)

 

print ( "The reversed string (using extended slice syntax) is:" , end = "")

print (reverse ( s))

Output:

 The original string is: Geeksforgeeks The reversed string (using extended slice syntax) is: skeegrofskee G 

Explanation: The extended slice suggests putting the "step" field as [start, stop, step] , and the field without specifying the beginning and end indicates the default value of 0 and the length of the line, respectively, and " -1 " indicates start from end and end to start, hence reversing the line.

Using reverse

# Python code to reverse the string
# using reversed ( )

 
# Function to reverse the string

def reverse (string):

string = "". join ( rev ersed (string))

return string

 

s = " Geeksforgeeks "

  

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

print (s)

 

print ( "The reversed string ( using reversed) is: " , end = " ")

print (reverse (s))

Output:

 The original string is: Geeksforgeeks The reversed string (using reversed) is: skeegrofskeeG 

Explanation: The reversed () function returns the reverse iterator of the given string and then its elements are concatenated into an empty string, separated with join (). And the reverse order string is generated.

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically