How to reverse a string in python using for loop?

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.

Code:

How to reverse a string in python using for loop

Output:

How to reverse a string in python using for loop

Explanation:

  1. We declare a string in a string variable
  2. We have taken an empty list variable
  3. 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.

  1. 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.
  2. 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.
  3. 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.

Code:

python using for loop

Output:

how python using for loop

Explanation:

The code remains same until the line 6th

  1. 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”.
  2. We are iterating the list items stored in “l” and accepting each word of the list in i.
  3. 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.

 

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

Your email address will not be published.