S2Q2 · Replace Consonants with Hash¶
⚡ Quick Reference
Type: Full I/O -multiline string processing
Core idea: for each character, if it's an alphabetic consonant replace with #, otherwise keep it.
n = int(input())
vowels = "aeiouAEIOU"
for _ in range(n):
line = input()
print("".join("#" if c.isalpha() and c not in vowels else c for c in line))
Key rules:
- Only alphabetic characters (isalpha()) can be consonants
- Vowels (aeiouAEIOU) stay unchanged
- Non-alphabetic characters (spaces, punctuation) stay unchanged
- Process and print line by line -no need to buffer all lines
Problem Statement¶
Problem (I/O type)
Read n lines. Replace every consonant with #. Vowels and non-alphabetic characters stay unchanged.
Example:
2
Hello World
Good Night
#e##o #o###
#oo# #i###
Understanding the problem¶
For each character, three cases:
| Character type | Action |
|---|---|
Vowel (a e i o u, upper or lower) |
Keep unchanged |
| Consonant (alphabetic, not a vowel) | Replace with # |
| Non-alphabetic (space, digit, punctuation) | Keep unchanged |
Tracing "Hello World":
| Char | isalpha() |
Vowel? | Output |
|---|---|---|---|
H |
✅ | ❌ | # |
e |
✅ | ✅ | e |
l |
✅ | ❌ | # |
l |
✅ | ❌ | # |
o |
✅ | ✅ | o |
|
❌ | - | |
W |
✅ | ❌ | # |
o |
✅ | ✅ | o |
r |
✅ | ❌ | # |
l |
✅ | ❌ | # |
d |
✅ | ❌ | # |
Result: #e##o #o###
Solution approaches¶
n = int(input())
vowels = "aeiouAEIOU"
for _ in range(n):
line = input()
print("".join("#" if c.isalpha() and c not in vowels else c for c in line))
Process each line as it's read. The generator expression handles all three cases in one ternary.
n = int(input())
vowels = "aeiouAEIOU"
for _ in range(n):
line = input()
result = ""
for c in line:
if c.isalpha() and c not in vowels:
result += "#"
else:
result += c
print(result)
Explicit loop -each condition step visible.
import string
n = int(input())
vowels = "aeiouAEIOU"
consonants = "".join(c for c in string.ascii_letters if c not in vowels)
table = str.maketrans(consonants, "#" * len(consonants))
for _ in range(n):
print(input().translate(table))
Build a translation table mapping every consonant to #. str.translate() applies it in one pass -no per-character checking in Python code.
Key takeaways¶
isalpha() + not in vowels = consonant
Two conditions together identify a consonant: the character must be alphabetic AND not a vowel. Spaces, digits, and punctuation fail isalpha() and are kept unchanged automatically.
Process line by line -no buffering needed
Unlike problems that need the full input before processing, this one can print each line immediately after reading it. No need to store all lines in a list.
str.translate() for character-level substitution
When replacing a fixed set of characters, str.maketrans() + str.translate() is the most efficient approach -it's a single O(n) pass with a lookup table, no Python-level loop.