0
0
Pythonprogramming~20 mins

Iterating over strings in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
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.