Python – Replace multiple characters at once
Last Updated :
08 Jan, 2025
Improve
Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least.
Using translate() with maketrans()
translate() method combined with maketrans() is the most efficient way to replace multiple characters.
s = "hello world"
replacements = str.maketrans({"h": "H", "e": "E", "o": "O"})
res = s.translate(replacements)
print(res)
5
1
s = "hello world"
2
3
replacements = str.maketrans({"h": "H", "e": "E", "o": "O"})
4
res = s.translate(replacements)
5
print(res)
Explanation:
- maketrans() function creates a mapping of characters to their replacements.
- translate() method applies the mapping to the string, replacing all specified characters efficiently.
- This method is highly optimized and works best for large strings.
Let’s explore some more ways and see how we can replace multiple characters at once in Python Strings.
Table of Content
Using replace() method in a loop
replace() method can be used repeatedly to handle multiple replacements.
s = "hello world"
replacements = {"h": "H", "e": "E", "o": "O"}
for old, new in replacements.items():
s = s.replace(old, new)
print(s)
7
1
s = "hello world"
2
3
replacements = {"h": "H", "e": "E", "o": "O"}
4
5
for old, new in replacements.items():
6
s = s.replace(old, new)
7
print(s)
Explanation:
- The replace() method handles one replacement at a time.
- Using a loop allows all specified characters to be replaced sequentially.
- While effective, this method may be slower due to repeated operations on the string.
Using regular expressions with sub()
Regular expressions provide a flexible way to replace multiple characters.
import re
s = "hello world"
pattern = "[heo]"
res = re.sub(pattern, lambda x: {"h": "H", "e": "E", "o": "O"}[x.group()], s)
print(res)
8
1
import re
2
3
s = "hello world"
4
5
pattern = "[heo]"
6
7
res = re.sub(pattern, lambda x: {"h": "H", "e": "E", "o": "O"}[x.group()], s)
8
print(res)
Explanation:
- The sub() method matches the pattern and replaces each match using a mapping.
- Regular expressions are powerful for complex patterns but introduce extra overhead.
- Best used when patterns are not straightforward.
Using list comprehension with join()
This method processes the string character by character and replaces specified ones.
s = "hello world"
replacements = {"h": "H", "e": "E", "o": "O"}
res = "".join(replacements.get(char, char) for char in s)
print(res)
6
1
s = "hello world"
2
3
replacements = {"h": "H", "e": "E", "o": "O"}
4
5
res = "".join(replacements.get(char, char) for char in s)
6
print(res)
Output
HEllO wOrld
Explanation:
- The get method of the dictionary checks if a character needs replacement.
- Characters not found in the dictionary remain unchanged.
- This method is less efficient for large-scale replacements due to character-wise iteration.