Python Arena
Step 2 of 5

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)
Input
Hello
Output
Word: Hello
H
e
l
l
o

Spaces 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)
Output
Vowels: 5

The 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)
Output
a_quiet,_calm_day

The 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"))
Output
3
0

Your task

Challenge 1 of 3

Fill in the blanks so the program counts how many times the letter a is in the text the user types, as a small or a capital letter:

Text: Banana Split
Letter a: 3

Challenge 2

Write the function hide_digits(text: str) -> str, which returns a copy of the text where every digit (0 to 9) is replaced with #. Everything else stays as it is. For example, hide_digits("Call 555-0123") returns 'Call ###-####'.

Challenge 3

What does this program print? Type each line it prints.