Bird
Raised Fist0
Pythonprogramming~20 mins

Iterating over strings in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
String Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of iterating and modifying a string
What is the output of this Python code?
text = "hello"
result = ""
for ch in text:
    if ch == 'l':
        result += 'L'
    else:
        result += ch
print(result)
Python
text = "hello"
result = ""
for ch in text:
    if ch == 'l':
        result += 'L'
    else:
        result += ch
print(result)
AheLLo
Bhello
CheLlo
DheLLoL
Attempts:
2 left
💡 Hint
Remember that the loop checks each character and replaces 'l' with 'L'.
Predict Output
intermediate
2:00remaining
Counting vowels in a string
What is the output of this code?
text = "Programming"
vowels = 'aeiouAEIOU'
count = 0
for char in text:
    if char in vowels:
        count += 1
print(count)
Python
text = "Programming"
vowels = 'aeiouAEIOU'
count = 0
for char in text:
    if char in vowels:
        count += 1
print(count)
A5
B4
C3
D2
Attempts:
2 left
💡 Hint
Check each letter if it is a vowel.
Predict Output
advanced
2:00remaining
Output of nested iteration over string
What does this code print?
word = "abc"
result = ""
for i in word:
    for j in word:
        if i == j:
            result += i.upper()
        else:
            result += j
print(result)
Python
word = "abc"
result = ""
for i in word:
    for j in word:
        if i == j:
            result += i.upper()
        else:
            result += j
print(result)
AAbcBaCcaB
BAbcaBcabC
CAbcBacCab
DABCabcabc
Attempts:
2 left
💡 Hint
Look at how the inner loop builds the string for each outer loop character.
Predict Output
advanced
2:00remaining
Result of modifying string characters conditionally
What is the output of this code?
text = "Data123"
result = ""
for ch in text:
    if ch.isalpha():
        result += ch.lower()
    else:
        result += '*'
print(result)
Python
text = "Data123"
result = ""
for ch in text:
    if ch.isalpha():
        result += ch.lower()
    else:
        result += '*'
print(result)
Adata***
BDATA123
Cdata123
DData***
Attempts:
2 left
💡 Hint
Check how letters and digits are handled differently.
🧠 Conceptual
expert
2:00remaining
Why strings are immutable in Python?
Which of the following is the main reason strings are immutable in Python?
ATo prevent strings from being garbage collected
BTo make string concatenation faster
CBecause strings are stored in a special memory area called stack
DTo allow strings to be used as dictionary keys and set elements safely
Attempts:
2 left
💡 Hint
Think about what properties dictionary keys need.

Practice

(1/5)
1. What does the following code do?
for letter in "hello":
print(letter)
easy
A. Prints each letter of the word 'hello' on a new line
B. Prints the whole word 'hello' once
C. Prints the length of the word 'hello'
D. Causes an error because strings can't be looped

Solution

  1. Step 1: Understand the for loop over a string

    The loop goes through each character in the string "hello" one by one.
  2. Step 2: Print each character

    Inside the loop, each letter is printed on its own line.
  3. Final Answer:

    Prints each letter of the word 'hello' on a new line -> Option A
  4. Quick Check:

    Loop over string prints letters individually [OK]
Hint: For loops over strings print letters one by one [OK]
Common Mistakes:
  • Thinking the whole string prints at once
  • Confusing string length with letters
  • Believing strings can't be looped
2. Which of the following is the correct syntax to loop over each character in the string text?
easy
A. for char to text:
print(char)
B. for char in range(text):
print(char)
C. for char in text:
print(char)
D. for i in text.length:
print(i)

Solution

  1. Step 1: Identify correct for loop syntax for strings

    In Python, to loop over characters in a string, use for variable in string:.
  2. Step 2: Check each option

    for char in text:
    print(char)
    uses correct syntax. The other options use invalid syntax like 'to' instead of 'in', range() on a string, or non-existent .length attribute.
  3. Final Answer:

    for char in text:
    print(char)
    -> Option C
  4. Quick Check:

    Correct for loop syntax over string is for char in text:
    print(char) [OK]
Hint: Use 'for char in string:' to loop letters [OK]
Common Mistakes:
  • Using range() on a string directly
  • Trying to use .length instead of len()
  • Using incorrect loop keywords
3. What is the output of this code?
word = "code"
result = ""
for ch in word:
    result += ch.upper()
print(result)
medium
A. code
B. CODE
C. Code
D. cODe

Solution

  1. Step 1: Loop through each letter in 'code'

    The loop takes each character: 'c', 'o', 'd', 'e'.
  2. Step 2: Convert each letter to uppercase and add to result

    Each letter is changed to uppercase ('C', 'O', 'D', 'E') and added to the empty string result.
  3. Final Answer:

    CODE -> Option B
  4. Quick Check:

    Uppercase each letter and join = CODE [OK]
Hint: Uppercase letters inside loop to build new string [OK]
Common Mistakes:
  • Not converting letters to uppercase
  • Printing original string instead of result
  • Using += without initializing result
4. Find the error in this code:
text = "hello"
for i in text:
    print(text[i])
medium
A. Variable 'text' is not defined
B. Missing colon after for loop
C. Loop should be 'for i in range(text):'
D. Using 'i' as index causes TypeError

Solution

  1. Step 1: Understand the loop variable 'i'

    Here, 'i' takes each character from 'text', so 'i' is a letter, not an index.
  2. Step 2: Using 'text[i]' causes error

    Since 'i' is a letter, using it as an index causes a TypeError because string indices must be integers.
  3. Final Answer:

    Using 'i' as index causes TypeError -> Option D
  4. Quick Check:

    Loop variable is letter, not index, so indexing fails [OK]
Hint: Loop variable is letter, not index; use range(len(text)) for indices [OK]
Common Mistakes:
  • Assuming loop variable is index
  • Trying to index string with a character
  • Confusing loop variable with range
5. Write code to count how many vowels are in the string sentence. Which code correctly does this?
hard
A. count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count)
B. count = 0 for i in range(len(sentence)): if sentence[i] == 'aeiou': count += 1 print(count)
C. count = 0 for ch in sentence: if ch == 'a' or 'e' or 'i' or 'o' or 'u': count += 1 print(count)
D. count = 0 for ch in sentence: if ch in ['a','e','i','o','u']: count = count + 1 print(count)

Solution

  1. Step 1: Check vowel membership correctly

    count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count) checks if each character is in the string of vowels (both lowercase and uppercase), which is correct.
  2. Step 2: Verify counting logic

    count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count) increments count correctly when a vowel is found and prints the total count.
  3. Final Answer:

    count = 0 for ch in sentence: if ch in 'aeiouAEIOU': count += 1 print(count) -> Option A
  4. Quick Check:

    Use 'in' with vowel string and increment count [OK]
Hint: Use 'if ch in "aeiouAEIOU"' to check vowels [OK]
Common Mistakes:
  • Using '==' to compare with multiple vowels
  • Checking membership incorrectly with list without uppercase
  • Not incrementing count properly