In this article we will see how to reverse a string in python using for loop also we will different ways in which we can store the output, example the output can be stored in the string itself or may be a list or may be a tuple.
We highly encourage you to read our list method article and in it particularly reverse method, because we will be using it.
Reverse a string in python using for loop and storing result in the list.
- We declare a string in a string variable
- We have taken an empty list variable
- Declaring a for loop and iterating It over string variable
Now each word in the string will be iterated and in each iteration, a single word will be stored in I, and in the next iteration, the next word will be stored in i.
- We have used the append() method of the list with list variable “l” and appended each word stored in i. to know more how appends work read our append() method.
- Now there is a simple method associated with a list using which we can easily reverse the contents of any list, and that’s what we have used online 6.
- The reverse list result is stored in a list variable called “l”, and we have printed it as it is.
Reverse a string in python using for loop and storing the result in another string.
The code remains same until the line 6th
- Now we have got a reverse string in the list variable called “l” from the previous loop, and we have declared an empty string variable called “string2”.
- We are iterating the list items stored in “l” and accepting each word of the list in i.
- We have used + operator on a string, the way we have used it is very important first we have assigned the value stored in i and then used + operator, so what it does is it concat it joins the previous string value to the new one, it does not overwrite it.
- And here simply we have printed the output.