How to Iterate Through Python String Characters With Examples

Last Updated on June 17, 2021 by Roshan Parihar

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 a 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.

Output

H
e
l
l
o

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 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.

Bonus: download a Free Python cheat sheet that will show you 20+ most important examples to learn in Python.

Using While Loop To Get Each Character

In addition to the 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.

Output

S
a
v
e

m
e

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 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(“”).

Output

S
h
u
t

u
p

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.

I hope you like this tutorial on how to iterate through python string.

DOWNLOAD Free PYTHON CHEAT SHEET

References