How to Loop Over a String in Python
A string is a chain of characters, where every character is at a particular index and can be accessed individually.
In this tutorial, we loop over a string and print individual characters in Python.
Use the for
Loop to Loop Over a String in Python
The for
loop is used to iterate over structures like lists, strings, etc. Strings are inherently iterable, which means that iteration over a string gives each character as output.
For example,
for i in "String":
print(i)
Output:
S
t
r
i
n
g
In the above example, we can directly access each character in the string using the iterator i
.
Alternatively, we can use the length of the string and access the character based on its index.
For example,
Str_value = "String"
for index in range(len(Str_value)):
print(Str_value[index])
Output:
S
t
r
i
n
g
The enumerate()
function can be used with strings. It is used to keep a count of the number of iterations performed in the loop. It does it by adding a counter to the iterable. It returns an object containing a list of tuples that can be looped over.
For example,
for i, j in enumerate("string"):
print(i, j)
Output:
0 s
1 t
2 r
3 i
4 n
5 g
Use the while
Loop to Loop Over a String in Python
The while loop is used just like the for loop for a given set of statements until a given condition is True. We provide the string’s length using the len()
function for iterating over a string.
In the while loop, the upper limit is passed as the string’s length, traversed from the beginning.
The loop starts from the 0th index of the string till the last index and prints each character.
For example,
Str_value = "String"
i = 0
while i < len(Str_value):
print(Str_value[i])
i = i + 1
Output:
S
t
r
i
n
g