To replace multiple characters in a string is a common task in Python. Here are a few clean and efficient ways to do it.
1. Using str.translate()
with str.maketrans()
Solution that works without looping or regex is translate
:
text = "hello world! hello winners!!"
replacements = str.maketrans("hw!", "HW?")
result = text.translate(replacements)
print(result)
result:
Hello World? Hello Winners??
- Best for single-character replacements.
- Fast and clean.
2. Using replace()
in a loop
text = "hello world!"
replacements = {"h": "H", "w": "W", "!": "."}
for old, new in replacements.items():
text = text.replace(old, new)
print(text)
After the replacement of the multiple chars at once:
Hello World.
- Works for replacing multiple characters or substrings.
- Custom replacements and filtering
- Flexible, readable.
3. Using Regular Expressions (advanced)
Using regex could handle advanced searches:
import re
text = "hello world!"
replacements = {"h": "H", "w": "W", "!": "."}
pattern = re.compile("|".join(map(re.escape, replacements)))
result = pattern.sub(lambda m: replacements[m.group(0)], text)
print(result)
Replace multiple chars with regex:
# Hello World.
- Ideal for complex replacements or overlapping patterns.
- Could have performance issues