In this tutorial, learn how to iterate through python string. You can loop through string variable in Python with for loop or while loop. Use direct string to loop over string in Python.
The method prints each letter of string in a single line after the loop. You have to use the print statement to print each letter one by one.
Iterate Through Python String Characters with For Loop
You can use for loop of Python to iterate through each element of the string. The iteration of the loop depends upon the number of letters in the string variable. The loop also counts the space to make a loop iterate in Python.
See the example below to perform a loop iteration using the for loop of Python.
myString = "Hello";
for str in myString:
The above example showing the output of a python loop on the string. There is 5 letter in the string without any space. The iteration also performs for 5 times and print each letter in each line in the output.
Each letter of the string gets printed in a single line. Check the above output about printed string after the loop or iteration.
Using While Loop To Get Each Characters
In addition to above for loop, you can iterate through python string using while loop also. To iterate through the while, you have to follow the below-given example.
The example requires a variable to initialize with zero(0) at first. After that, a while loop start which iterates through the string using the python len() function. You may also like to read how to find the length of the list in Python.
myString = "Save me";
while str < len(myString):
str += 1
The above example showing the iteration through the string and the output. The output contains the single letter printed in every single line with space also.
The above all example prints the output using the string variable calls under for a loop. However, you can also iterate through the string by calling it directly with the for loop.
Loop Over String Characters Directly Without Variable in Python
If you want to perform the iteration by calling the string directly with the for loop. You have to use the below-given example showing the string enclosed within the double quotes(“”).
for str in "Shut up":
The above example also gives the letters of the string in the output. However, this system may not work with the while loop in Python. So, you have to use the above example by changing the string as per your requirement.
Hope, you like this tutorial of how to iterate through python string. If you have any query regarding the tutorial, please comment below.
- Thispointer Tutorial on loop over string characters in Python
- Stackoverflow Discussion on iteration over string characters using Python
Also tell me, which method you are using to loop through the string in Python.