0
0
Pythonprogramming~5 mins

Iterating over strings in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to iterate over a string in Python?
Iterating over a string means going through each character one by one, like reading a word letter by letter.
Click to reveal answer
beginner
How do you write a simple loop to print each character of the string "hello"?
Use a for loop like this:<br>
for char in "hello":
    print(char)
Click to reveal answer
beginner
Can you change characters of a string by iterating over it?
No, strings are like frozen words. You can read each letter, but you cannot change them directly because strings are immutable.
Click to reveal answer
beginner
What will this code print?<br>
for c in "abc":
    print(c.upper())
It prints:<br>
A
B
C
<br>Each letter is converted to uppercase before printing.
Click to reveal answer
intermediate
How can you get the index of each character while iterating over a string?
Use the enumerate() function:<br>
for index, char in enumerate("hello"):
    print(index, char)
Click to reveal answer
What does the following code do?<br>
for ch in "cat":
    print(ch)
APrints each letter of the word 'cat' on a new line
BPrints the whole word 'cat' three times
CPrints the word 'cat' once
DCauses an error
Which statement is true about strings in Python?
AYou can change characters in a string by assigning new values
BStrings are lists of characters that can be modified
CStrings are immutable, so you cannot change characters directly
DStrings cannot be iterated over
How do you get both the index and character when looping over a string?
AUse the split() method
BUse a normal for loop with range and indexing
CUse the len() function only
DUse the enumerate() function
What will this code print?<br>
for c in "dog":
    print(c.upper())
AD<br>O<br>G
Bdog
CDOG
Dd<br>o<br>g
Which of these is NOT a way to iterate over a string?
AUsing a while loop with an index
BUsing the string's reverse() method
CUsing enumerate() in a for loop
DUsing a for loop directly on the string
Explain how to loop through each character in a string and print it.
Think about reading a word letter by letter.
You got /3 concepts.
    Describe why you cannot change characters in a string while iterating over it.
    Strings are like frozen words.
    You got /3 concepts.