Looping through a string
len( ) function
The len()
function is a Python built-in function that reports the size, or length, of its input, which is usually a string
or a list
.
s = 'Apple pie'
print(len(s)) # 9
print(len('Banana float')) # 12
len('') # 0 (an empty string)
print(len('donuts') + len('pan cake')) # 14
Looping through a string
Here we show two ways to iterate over characters in a string:
Use the string index number to loop through the string
One way to iterate over a string is to use for i in range(len(str)):
. In this loop, the variable i
receives the index so that each character can be accessed using str[i]
.
Example:
t = 'World'
for i in range(len(t)):
print(t[i])
Console result:
W
o
r
l
d
Directly loop through each item in the string
Another way to iterate over a string is to use for item in str:
. The variable item
receives the character directly so you do not have to use the index. Since this loop does not need the index value of each character, this loop format is simpler and is preferred over the previous one.
Example:
s = 'Buzz'
for char in s:
print(char)
Console results:
B
u
z
z