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"))
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 print(res)
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.