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 Python - Replacing Nth occurrence of multiple characters in a String with the given character Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This app 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 Check If Dictionary Value Contains Certain String with Python We need to check if the value associated with a key in a dictionary contains a specific substring. For example, if we have a dictionary of user profiles and we want to check if any userâs description contains a particular word, we can do this easily using various methods. Letâs look at a few ways to 4 min read Python - Convert Dictionary Object into String In Python, there are situations where we need to convert a dictionary into a string format. For example, given the dictionary {'a' : 1, 'b' : 2} the objective is to convert it into a string like "{'a' : 1, 'b' : 2}". Let's discuss different methods to achieve this:Using strThe simplest way to conver 2 min read How to Change Values in a String in Python The task of changing values in a string in Python involves modifying specific parts of the string based on certain conditions. Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we mi 2 min read Python - Converting list string to dictionary Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-val 3 min read Like