Home Tutorials How To Reverse A String In Python Using For Loop

How To Reverse A String In Python Using For Loop

0

The Unicode character collection in Python is called a string. Although Python contains many functions for manipulating strings, the built-in “reverse()” function is not supported by the Python string library so let’s go and learn reverse a string in python using for loop.

However, there are other methods for reversing the string. To reverse the Python String, we define the following procedure.

Reverse A String In Python Using For Loop

  • Using for loop
  • Using while loop
  • One function is the slice operator
  • Using the reversed() function
  • Using the recursion
  • Making use of for loop
  • Using the for loop, we will reverse the given string.

def reverse_string(str):  
    str1 = ""
    for i in str:  
        str1 = i + str1  
    return str1
     
str = "WholeBlogs"  
print("The original string is: ",str)  
print("The reverse string is: ",reverse_string(str))

Output:

The original string is: WholeBlogs
The reverse string is: sgolBelohW

Reverse A String In Python Using For Loop

We declared the reverse string() function and gave the str argument in the previous code. We declared an empty string variable str1 in the function body to retain the inverted string.

The for loop then looped through each character in the given string, connecting them at the beginning and saving them to the str1 variable. It displayed the outcome on the screen.

Utilizing the while loop

A while loop can also be used to reverse a string. Have a look at this link illustration.

As an example,

str = "WholeBlogs" 
print ("The original string  is : ",str)   
reverse_String = ""
count = len(str)
while count > 0:   
    reverse_String += str[ count - 1 ]
    count = count - 1 
print ("The reversed string using a while loop is : ",reverse_String)

Output

The original string is : WholeBlogs
The reversed string using a while loop is : sgolBelohW

Using while loops

Read More: The Best Way to Strip Punctuation from a String using Python

  1. To reverse a string in Python, you can use a for a loop.
  2. The for loop iterates through each character in the string and reverses it.
  3. This method is simple and easy to understand.
  4. It also runs faster than some of the other methods available.

LEAVE A REPLY

Please enter your comment!
Please enter your name here