Python - Replace Different Characters in String at Once
Last Updated :
29 Jan, 2025
The task is to replace multiple different characters in a string simultaneously based on a given mapping. For example, given the string: s = "hello world" and replacements = {'h': 'H', 'o': '0', 'd': 'D'} after replacing the specified characters, the result will be: "Hell0 w0rlD"
Using str.translate()
str.translate() method in Python efficiently replaces characters in a string based on a translation table created using str.maketrans(). str.maketrans() generates a mapping of characters to their replacements while str.translate() applies this mapping to transform the string.
Python
s = 'geeksforgeeks is best'
# Initializing mapping dictionary
d = {'e': '1', 'b': '6', 'i': '4'}
# Using translate() with maketrans()
res = s.translate(str.maketrans(d))
print(res)
Outputg11ksforg11ks 4s 61st
Explanation:
- str.maketrans(d) converts the dictionary d into a translation table that maps characters to their replacements.
- s.translate(str.maketrans(d)) applies the translation table to string s using translate().
Using List Comprehension
List comprehension is a simple way to create new lists by applying an expression to each item. For string manipulation, it conditionally replaces characters eliminating the need for loops and making the code cleaner and more readable.
Python
s= 'geeksforgeeks is best'
d = {'e': '1', 'b': '6', 'i': '4'}
# Replacing characters using list comprehension
res = ''.join([d[char] if char in d else char for char in s])
print(res)
Outputg11ksforg11ks 4s 61st
Explanation:
- List comprehension iterates over each character in s and if the character is found in the dictionary d. It is replaced with its mapped value otherwise the character remains unchanged.
- ''.join([...]) combines the transformed list of characters back into a single string.
Using Regular Expressions
This method uses re.sub() function from Python's re module to replace characters in a string. It allows us to define a pattern to match characters and replace them efficiently. This is a flexible approach, especially when working with multiple replacements in one go.
Python
import re
s = 'geeksforgeeks is best'
d = {'e': '1', 'b': '6', 'i': '4'}
# using re.sub() to replace characters
res = re.sub('|'.join(re.escape(k) for k in d), lambda match: d[match.group(0)], s)
print(res)
Outputg11ksforg11ks 4s 61st
Explanation:
- '|'.join(re.escape(k) for k in d) creates a regular expression that matches any of the keys from the dictionary ('e', 'b', and 'i').
- lambda anonymous function returns the corresponding mapped value from the dictionary d for each match.
- re.sub() applies the substitution to the string, replacing characters based on the dictionary mapping.
Using str.replace()
This method iterates over a small mapping dictionary, using str.replace() to replace characters in the string based on the dictionary. It’s simple and effective for small-scale replacements, but can be less efficient for larger strings or complex replacements.
Python
s = 'geeksforgeeks is best'
d = {'e': '1', 'b': '6', 'i': '4'}
# using replace() in a loop
res = s
for key, value in d.items():
res = res.replace(key, value)
print(res)
Outputg11ksforg11ks 4s 61st
Explanation:
- res = s: variable res is initialized with the value of s .
- for key, value in d.items() iterates through each key-value pair in the dictionary d. For each pair, the loop performs a replacement in the string.
- res = res.replace(key, value) here in each iteration, the replace() method is called on res replacing all occurrences of key with value. After each replacement, the updated string is stored back in res.
Similar Reads
Replace a String character at given index in Python In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index.Pythons = "hello" idx = 1 rep
2 min read
Python - Replace multiple characters at once 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 mult
2 min read
Remove Multiple Characters from a String in Python Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Letâs explore the different ways to achieve this in det
2 min read
Remove Character in a String at a Specific Index in Python Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a
2 min read
Iterate over characters of a string in Python In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Letâs explore this approach.Using for loopThe simplest way to iterate over the characters in
2 min read