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 Replace Characters in Strings in Pandas DataFrame In this article, we are going to see how to replace characters in strings in pandas dataframe using Python. We can replace characters using str.replace() method is basically replacing an existing string or character in a string with a new one. we can replace characters in strings is for the entire 3 min read 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 Find the first repeated word in a string in Python using Dictionary We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U 3 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 Python | Words extraction from set of characters using dictionary Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It che 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 Turning a Dictionary into XML in Python XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elemen 3 min read How to Create a Dictionary in Python The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa 3 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 Like