Skip to content

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

  • by

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

For 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"))


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 the string.

str1 = "ABC XYZ"

res = ""
count = len(str1)

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


Output: ZYX CBA

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *