Register Login

5 Different Ways to Reverse String in Python

Updated Mar 03, 2020

In python string library, there is no in-build “reverse” function to reverse a string, but there are many different ways to reverse a string. 

In this article, you will learn 5 different ways to reverse the string in Python.

1) Using for Loop

Example:

# Program to explain reverse string or sentence 
# Using for loop
# Reverse String without using reverse function

# Define a function
def reverse_for(string):
    # Declare a string variable 
    rstring = ''

    # Iterate string with for loop
    for x in string:
        # Appending chars in reverse order
        rstring = x + rstring
    return rstring

string = 'Stechies'

# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse_for(string))

Output:

Original String:  Stechies
Reverse String:  seihcetS

Explanation:

In the above example, we use for loop to iterates through every character of the string and append each character in the beginning, in order to get the final string as a reverse string.

The above program will start its execution from the statement string = ‘stechies’. So at first, our string will be initialized with the value ‘stechies’. The next line prints out the original value of the string. The last line of the code. Displays the value of the reversed string by calling the ‘reverse_for’ function, and passing the string variable as an argument. When the function is called, the function definition will be executed.

In the function definition, we have declared a new variable ‘rstring’ that stores the reversed string. In the next line, we used a for loop that iterates over the variable 'string'.

When the control goes to the for loop, the value of ‘i’ is assigned ‘s’. Inside the for loop we concatenated the value of ‘i’ to the variable ‘rstring’. After concatenation, the control goes back to the for loop and the value of ‘i’ then becomes ‘t’. and then ‘t’ is concatenated to the variable stored in ‘string’. Now the value of ‘rstring’ is ‘ts’. Likewise, other values get concatenated to rstring. Thus we get the reversed string ‘seihcets’.

2) Using while Loop

Example:

# Program to explain reverse string
# Using while loop

# Define a function
def reverse_while(string):
    # Declare a string variable 
    rstring = ''

    # We will calculate string length
    # And subtract 1 because string index start with 0
    length = len(string) - 1
    # We will run the loop with last string index 
    while length >= 0:
        print('String Index: ',string[length],' - ', length)

        #Appending chars in reverse order
        rstring = rstring + string[length]

        # Decrements string index by 1
        length = length - 1
    return rstring

string = 'Stechies'
# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse_while(string))

Output:

Original String:  Stechies
String Index:  s  -  7
String Index:  e  -  6
String Index:  i  -  5
String Index:  h  -  4
String Index:  c  -  3
String Index:  e  -  2
String Index:  t  -  1
String Index:  S  -  0
Reverse String:  seihcetS

Explanation:

In the above example, we first subtracting the length of the string by one because the string index starts from zero. 

The code iterates through every element of string in reverse order using while loop and append character in the final string in reverse order. In the first line, the def keyword is used for defining a function called reverse_while(string) that takes a parameter string.

Inside it, a rstring variable is assigned an empty string. A variable called length is assigned length of the string parameter subtracted by 1. This is done by using the len() method.

A while loop is executed for checking whether the length variable has a value greater than 0. While this condition is True, this line is executed:

print('String Index: ',string[length],' - ', length) 

This displays the characters of the string along with their index values, starting from the last index. The next line appends the characters in reverse order into the rstring variable. Then the line length = length – 1 decrements the index of the string by 1. The final value of the rstring variable is printed to the screen.
The string variable is assigned the value “Stechies”.

This value is printed out in the next line using the print() method. Then another print() method is used for printing the reversed value of this string by calling the reverse_while(string) method within the print statement.

3) Using Slicing

Example:

# Program to explain reverse string
# Using Slicing

# Define a function
def reverse_slice(string):
    return string[::-1]

string = 'Stechies'
# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse_slice(string))

Output:

Original String:  Stechies
Reverse String:  seihcetS

Explanation:

In the example, we are using the slicing to slice the string from start to end and moving backwards to the beginning of the string.

Slice provides steps such as [start,stop,step]. As you can see in the above example we did not give any filed to start & stop, so it will take the default value as 0 for start and stop and (-1) to step respectively which denotes starting from the end and stop at the start while reversing the string.

In the above program, we created a function ‘reverse_slice’ that takes ‘string’ as a parameter. And uses slicing operator to print the reverse of a string. Here string[::-1] statement means, slicing starts from the end of the string. since we did not specify the ‘start’ and end at position 0. -1 specifies the step, in this case, ‘-1’ means one step back.

At last the print statement calls the function and displays the reversed string. 

4) Using join() and reversed() Methods

Example:

# Program to explain reverse string
# Using for reversed() function 

# Define a function
def reverse_rev(string):
    # Join reverse object of original string
    rstring = ''.join(reversed(string))
    return rstring

string = 'Stechies'

# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse_rev(string))

Output:

Original String:  Stechies
Reverse String:  seihcetS

Explanation:

In the above example, you can see that we pass the string using reversed() method to iterate every element of the string in reverse order and by using join() function, we join the element of the string.

Here, a reverse_rev(string) method is defined using the def keyword. The value of the string argument is passed to the reversed() method. The reversed characters of the string are joined using the join() method where ‘’ is the string and reversed(string) is iterable. The reversed value of the string is assigned to the rstring variable. The function then returns this variable.

The next line prints out the original value of the string, i.e. Stechies. The reversed string is printed in the subsequent line by calling the reverse_rev(string) method.

5) Using List reverse()

Example:

# Program to explain reverse string
# Using for reverse() function 

# Define a function
def reverse_list(string):
    # Convert string to list
    rstring  = list(string)

    # Print List
    print(rstring)

    # Reverse List with reverse() function
    rstring.reverse()

    # Print reverse list
    print(rstring)

    # Convert list to string with join() function 
    return ''.join(rstring)

string = 'Stechies'

# Print Original and Reverse string
print('Original String: ', string)
print('Reverse String: ', reverse_list(string))

Output:

Original String:  Stechies
['S', 't', 'e', 'c', 'h', 'i', 'e', 's']
['s', 'e', 'i', 'h', 'c', 'e', 't', 'S']
Reverse String:  seihcetS

Explanation:

In the above example we are converting a string to a list and reversing the list using reverse() function then converting the list to string using join() method.

Here, a reverse_list(string) method is defined that takes in a single parameter called a string. The parameter is then converted into a list using the list() method. The value is then assigned to a variable called rstring. This variable is printed to the screen.

After that, the contents of the rstring variable are reversed using the code rstring.reverse(). The print() method prints the rstring value in the next line.
This reversed list is then joined using the join() method and is the final value is returned by the method. In the next line, a variable string is initialized with the string “Stechies”.

This value is printed out in the next line. The last line displays the value of the reversed string. This print() statement prints the result of calling the method reverse_list(string). Here, the string value “Stechies” is passed as the argument.

Conclusion

Define the functions properly before using them. It is better to use different names for arguments and parameters to avoid confusion.  


×