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) OutputHellO 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.Table of ContentUsing List Comprehension with join()Using For LoopUsing Regular ExpressionsUsing 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) OutputGFG!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 LoopThis 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) OutputHellO 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 ExpressionsIf 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) OutputHellO 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. Comment More infoAdvertise with us Next Article Replacing Characters in a String Using Dictionary in Python K khushidg6jy Follow Improve Article Tags : Python python Practice Tags : pythonpython Similar Reads How to replace words in a string using a dictionary mapping In Python, we often need to replace words in a string based on a dictionary mapping, where keys are words to replace and values are their replacements. For example, given the string "the quick brown fox jumps over the lazy dog" and the dictionary {"quick": "slow", "lazy": "active"}, we want to repla 4 min read Create a Nested Dictionary from Text File Using Python We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dic 3 min read Convert Unicode String to Dictionary in Python Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is convert 2 min read Python - Replace all occurrences of a substring in a string Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence 2 min read Map function and Lambda expression in Python to replace characters Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 wit 2 min read Like