Loops and Text
In the lesson on lists, you saw that you can read the characters of a text by index, just like the elements of a list: word[0] is the first character. The for loop works with text too. In each iteration, the variable holds the next character:
word = "Hello"
for character in word:
print(character)This prints:
H
e
l
l
oThe patterns from the previous exercises work with text as well. This loop counts the letters l:
word = "Hello"
count = 0
for character in word:
if character == "l":
count += 1
print("Number of l:", count)Number of l: 2Remember that uppercase and lowercase letters are different characters: "H" == "h" is False. And a space is a character too, so for "Hi there", the loop would run 8 times.
Instructions
- 1
Go through
textwith a loop and print each of its characters on its own line. - 2
Below that, count how many times the letter
rappears intext: create a variablecountwith the value0, go through the text again and increasecountby 1 for everyr. After the loop, printNumber of r:andcount. The output isNumber of r: 2.