In this tutorial, you will learn to reverse a string in Python using For Loop.
If you don’t want to use an inbuilt function to reverse a string and simply want to learn how to reverse any string using a For Loop or While Loop, it’s quite simple. All you have to worry about is using the correct concatenation when joining the string letters.
Let us see in the below example codes to reverse a string using any type of loop method either for or while in Python.
Using For Loop To Reverse A String In Python
Because there isn’t much to explain about the for loop, let’s jump right into the example code. All I’m going to do is add a new string variable to store the string in reverse order as the loop runs.
#Initializing the String To Reverse inputString = "Reverse" #Variable To Store String revString = "" for letters in inputString: #Concatenating the String in Reverse Order revString = letters + revString #Printing the Reverse String print(revString)
As seen in the preceding example, the reverse word is printed for the input string. But what if you have a sentence and only want to reverse the words rather than the letters?
Reverse A Sentence In Python Using For Loop
Let’s look at an example of using For Loop to reverse a word in a sentence rather than the letters of the words.
#Initializing the String To Reverse inputString = "Reverse This String" #Variable To Store String revString = "" #Add the Words after reverse revWord = "" #Variable to store revSentence revSentence = "" for letters in inputString: #Concatenating the String in Reverse Order revString = letters + revString for letter in revString: if letter == " ": revSentence = revSentence + revWord + " " revWord = "" else: revWord = letter + revWord revSentence = revSentence + revWord #Printing the Reverse Sentence print(revSentence)
String This Reverse
I hope you gained an understanding of how to reverse a string in Python using the For Loop. I’ve provided two code examples for two different problems that can arise when reversing a string in this section.
If you know of a better method than the one discussed above, please let me know in the comments section and I will be happy to include it here.
If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.