Open In App

Replacing Characters in a String Using Dictionary in Python

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "HellO wOrld". Let's explore several ways to achieve this.

Using str.translate() with str.maketrans()

This method uses Python's built-in str.translate() and str.maketrans() methods to replace characters efficiently.

Python
s = "hello world"
replacements = {'h': 'H', 'o': 'O'}

# Create translation table and replace characters
res = s.translate(str.maketrans(replacements))

print(res)

Output
HellO wOrld

Explanation:

  • str.maketrans() method creates a translation table from the dictionary.
  • str.translate() method applies the translation table to the string, replacing the specified characters.

Let's explore some more ways and see how we can replace characters in a string using dictionary in Python.

Using List Comprehension with join()

We can iterate through the string and replace characters based on the dictionary using a list comprehension.

Python
s = "hello world"
replacements = {'h': 'H', 'o': 'O'}

# Replace characters and join back to a string
res = ''.join(replacements.get(c, c) for c in s)

print(res)

Output
GFG!

Explanation:

  • The get method retrieves the replacement for a character if it exists in the dictionary; otherwise, it keeps the original character.
  • join() method combines the updated characters into a single string.

Using For Loop

This approach uses a traditional for loop to iterate through the string and replace characters.

Python
s = "hello world"
replacements = {'h': 'H', 'o': 'O'}

res = ""

# Replace characters manually
for c in s:
    res += replacements.get(c, c)

print(res)

Output
HellO wOrld

Explanation:

  • for loop iterates through each character in the string.
  • Get method checks if the character has a replacement; otherwise, it appends the original character.

Using Regular Expressions

If the dictionary keys contain multiple characters or patterns, re.sub() can be used for replacements.

Python
import re

s = "hello world"
replacements = {'h': 'H', 'o': 'O'}

# Create a regular expression pattern from the dictionary keys
pattern = re.compile('|'.join(re.escape(k) for k in replacements))

# Replace characters using the pattern
res = pattern.sub(lambda x: replacements[x.group(0)], s)

print(res)

Output
HellO wOrld

Explanation:

  • re.escape() method ensures special characters in the dictionary keys are escaped properly.
  • sub() method replaces matches with corresponding values from the dictionary.

Next Article
Article Tags :
Practice Tags :

Similar Reads