In this article, we will discuss different ways to replace multiple characters in a string in Python.
Table of Contents:
- Replace multiple characters in a string using the replace()
- Replace multiple characters in a string using the translate ()
- Replace multiple characters in a string using regex
- Replace multiple characters in a string using for loop
Suppose we have a string,
sample_string = "This is a sample string"
Now we want the following characters to be replaced in that string,
- Replace all occurrences of ‘s’ with ‘X’.
- Replace all occurrences of ‘a’ with ‘Y’.
- Replace all occurrences of ‘i’ with ‘Z’.
- Python: Replace multiple characters in a string using for loop
There are different ways to do this. Let’s discuss them one by one,
Python: Replace multiple characters in a string using the replace()
In Python, the String class (Str) provides a method replace(old, new) to replace the sub-strings in a string. It replaces all the occurrences of the old sub-string with the new sub-string.
In Python, there is no concept of a character data type. A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string.
sample_string = "This is a sample string" char_to_replace = {'s': 'X', 'a': 'Y', 'i': 'Z'} # Iterate over all key-value pairs in dictionary for key, value in char_to_replace.items(): # Replace key character with value character in string sample_string = sample_string.replace(key, value) print(sample_string)
Output:
ThZX ZX Y XYmple XtrZng
It replaced all the occurrences of,
- Character ‘s’ with ‘X’.
- Character ‘a’ with ‘Y’.
- Character ‘i’ with ‘Z’.
As strings are immutable in Python and we cannot change its contents. Therefore, replace() function returns a copy of the string with the replaced content.
Python: Replace multiple characters in a string using the translate ()
We can also replace multiple characters in string with other characters using translate() function,
sample_string = "This is a sample string" char_to_replace = {'s': 'X', 'a': 'Y', 'i': 'Z'} # Replace all multiple characters in a string # based on translation table created by dictionary sample_string = sample_string.translate(str.maketrans(char_to_replace)) print(sample_string)
Output:
ThZX ZX Y XYmple XtrZng
We created that translation table from a dictionary using Str.maketrans() function. We then passed that translation table as an argument to the translate() method of Str, which replaced following characters in string based on that translation table,
- Character ‘s’ gets replaced with ‘X’.
- Character ‘a’ gets replaced with ‘Y’.
- Character ‘i’ gets replaced with ‘Z’.
As strings are immutable in Python and we cannot change its contents. Therefore translate() function returns a copy of the string with the replaced content.
Python: Replace multiple characters in a string using regex
Python provides a regex module (re), and in this module, it provides a function sub() to replace the contents of a string based on patterns. We can use this re.sub() function to substitute/replace multiple characters in a string,
import re sample_string = "This is a sample string" char_to_replace = {'s': 'X', 'a': 'Y', 'i': 'Z'} # Replace multiple characters (s, a and i) in string with values in # dictionary using regex sample_string = re.sub(r"[sai]", lambda x: char_to_replace[x.group(0)], sample_string) print(sample_string)
Output:
ThZX ZX Y XYmple XtrZng
Here we passed a pattern r’[sai]’ as the first argument, which matches all occurrences of character ‘s’, ‘a’ and ‘i’. As the second argument in the sub() function, we passed a lambda function, which fetches the matched character from the match object and then returns the value associated with it from the dictionary. Then as the third argument, we passed the original string.
Now for each character in the string that matches the pattern, it calls the lambda function, which gives the replacement character. Then the sub() function replaces that character in the string.
It replaced all the occurrences of,
- Character ‘s’ with ‘X’.
- Character ‘a’ with ‘Y’.
- Character ‘i’ with ‘Z’.
As strings are immutable in Python and we cannot change its contents. Therefore sub() function of the regex module returns a copy of the string with the replaced content.
Python: Replace multiple characters in a string using for loop
Initialize a new empty string and then iterate over all characters of the original string. During iteration, for each check, if the character exists in the dictionary char_to_replaced or not,
- If yes, the fetch replacement of that character and add to the new string.
- If no, then add the character to the new string.
For example,
sample_string = "This is a sample string" char_to_replace = {'s': 'X', 'a': 'Y', 'i': 'Z'} result = '' # Iterate over all characters in string for elem in sample_string: # Check if character is in dict as key if elem in char_to_replace: # If yes then add the value of that char # from dict to the new string result += char_to_replace[elem] else: # If not then add the character in new string result += elem print(result)
Output:
ThZX ZX Y XYmple XtrZng
It replaced all the occurrences of,
- Character ‘s’ with ‘X’.
- Character ‘a’ with ‘Y’.
- Character ‘i’ with ‘Z’.
As strings are immutable in Python and we cannot change its contents. Therefore, we created a new copy of the string with the replaced content.
Summary
We can replace multiple characters in a string using replace() , regex.sub(), translate() or for loop in python.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.