How to reverse a string in Python using for loop | Example code

Python string library doesn’t have the in-built reverse() function. But Using for loop or while loop you can reverse a string in Python.

Example reverse a string in Python using for loop

Simple Python example code will reverse the given string using for loop.

Note: Python string is not mutable, but you can build up a new string while looping through the original one:

Using for loop

The for loop iterated every element of the given string, join each character in the beginning, and store it in the variable.

def reverse(text):
    rev_text = ""
    for char in text:
        rev_text = char + rev_text
    return rev_text


print(reverse("ABC DEF"))

Output:

How to reverse a string in Python using for loop

Using while loop

Initialized a while loop with a value of the string and In each iteration, the value of str[count – 1] concatenated to string.

str1 = "ABC XYZ"

res = ""
count = len(str1)

while count > 0:
    res += str1[count - 1]
    count = count - 1

print(res)

Output: ZYX CBA

Do comment if you have any doubts and suggestions on this Python reverse string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.