Open In App

Python – Replace multiple characters at once

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
s = "hello world"

replacements = str.maketrans({"h": "H", "e": "E", "o": "O"})
res = s.translate(replacements)
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.

Using replace() method in a loop

replace() method can be used repeatedly to handle multiple replacements.

Python
s = "hello world"

replacements = {"h": "H", "e": "E", "o": "O"}

for old, new in replacements.items():
    s = s.replace(old, new)
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.

Python
import re

s = "hello world"

pattern = "[heo]"

res = re.sub(pattern, lambda x: {"h": "H", "e": "E", "o": "O"}[x.group()], s)
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.

Python
s = "hello world"

replacements = {"h": "H", "e": "E", "o": "O"}

res = "".join(replacements.get(char, char) for char in s)
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.


Next Article
Practice Tags :

Similar Reads