Going through a string
A for loop goes through a string too, one character at a time:
word = input("Word: ")
for char in word:
print(char)
HelloWord: Hello
H
e
l
l
oSpaces and punctuation are characters as well, so the loop sees them too. char is just a variable name; letter or c would work as well.
Counting characters
With a helper variable, the loop can count characters of some kind. Here in checks whether a character is one of the vowels in the string "aeiou":
text = "Programming is fun"
vowels = 0
for char in text.lower():
if char in "aeiou":
vowels += 1
print("Vowels:", vowels)
Vowels: 5The loop goes through text.lower(), a copy of the text in small letters, so a capital A would be counted as well.
Building a new string
A loop can also build a new string, character by character. Start with the empty string "" and add to it with +=:
text = "a quiet, calm day"
result = ""
for char in text:
if char == " ":
result += "_"
else:
result += char
print(result)
a_quiet,_calm_dayThe original string doesn't change: result is a new string, with an underscore wherever text has a space.
The same loops work in functions. A function that gets a string as a parameter goes through it in just the same way, and returns the count or the new string at the end:
def count_char(text: str, wanted: str) -> int:
count = 0
for char in text:
if char == wanted:
count += 1
return count
print(count_char("banana", "a"))
print(count_char("banana", "x"))
3
0