Skip to content
Home ยป Program to Reverse a string in python

Program to Reverse a string in python

Python program to reverse a string : The Python String is a collection of Unicode characters. Although Python contains several functions for manipulating strings, the Python string library does not provide the built-in reverse() function. However, there are other methods for reversing the string.

Reverse a string using For loop

def reverse_str(s):  
    str = ""  #empty string 
    for i in s:  
        str = i + str  
    return str    # Returning the reversed string
# Given String 
string = "SimilarGeeks"           
print("The original string is: ",string)  
print("The reverse string is",reverse_str(string))


The original string is: SimilarGeeks
The reverse string is skeeGralimiS


We declared the reverse_str() function and passed the s argument. We declared an empty string variable str in the function body, which will retain the reversed string. The for loop then iterated through each element of the given string, joining each character at the beginning and storing it in the str variable. The reverse order string will be returned to the caller function at the end of the iteration. Prints the result on the screen.

Reverse a string using While loop

string = "SimilarGeeks" 
print ("The original string  is : ",string) 
reverse_Str = "" 
count = len(string) # length of a string is stored in count variable
while count > 0:   
    reverse_Str += string[ count - 1 ]
    count = count - 1

print ("The reversed string is: ",reverse_Str)#Prints the reversed string   


The original string is : SimilarGeeks
The reversed string is: skeeGralimiS


We declared a string variable, which holds a string value. In while loop, for each iteration the value of string[count โ€“ 1] is concatenated to the reverse_Str and the count value is decremented. Prints the reverse string value.

Reverse a string using the slice ([]) operator

def reverse_str(string):   
    string = string[::-1]   
    return string   

str = "SimilarGeeks"  
print ("The original string  is : ",str)   
print ("The reversed string is : ",reverse_str(str))  


The original string is : SimilarGeeks
The reversed string is : skeeGralimiS


A slice operator typically accepts three parameters: start, stop, and step. We specified no for the start and end indexes, indicating that the start index is 0 and the end index is n-1 by default. The step size is -1, which means that the string continues the traversal from the end to the 1 index point.

Also Read:

Python program to count frequency of character in a string