How to Replace Multiple Characters in a String in Python [7 Ways]

Do you want to learn “How to replace multiple characters in a string in Python“? In this Python tutorial, we will explain 7 different methods to replace the characters in Python with some practical examples.

Replacing a string in Python is a concept of string manipulation. We’ve found 7 different methods to get the expected result.

These are the seven different methods to replace multiple characters in a Python string:

  1. Using nested replace() methods
  2. Using translate() with maketrans() methods
  3. Using re.sub()
  4. Using List Comprehension
  5. Using a dictionary
  6. Using re.subn() method.
  7. for loop

Replace multiple characters in a string in Python using replace() function.

The replace() method in Python replaces occurrences of a specified substring within a string with another. We use the nested replace method to replace multiple characters in a string.

Here is an example to replace multiple characters in a string in Python:

Code

phone_number = "(123) 456-7890"
cleaned_number = phone_number.replace("(", "").replace(")", "").replace("-", "")
print("Cleaned Number:", cleaned_number)

The provided code replaces (‘, ‘), and ‘-‘ characters from a phone number string, resulting in a cleaned number containing only digits.

Output

Cleaned Number: 123 4567890

Attached is a screenshot of my Python code executed in Visual Studio.

How to Replace Multiple Characters in a String in Python

Replace multiple characters at once using maketrans() in Python

The str.translate() method in Python is more efficient for replacing multiple characters in a string, especially when dealing with large datasets.

READ:  How to use Python While with Assignment[4 Examples]

It uses a translation table to map characters to replace multiple characters in a string.

Code:

import string

text = "_hello_, _world_!"
translation_table = str.maketrans("", "", string.punctuation)
cleaned_text = text.translate(translation_table)
print("Cleaned Text:", cleaned_text)

The code initializes a translation table using the maketrans() method with empty strings for both the ‘deletechars’ and ‘replchars‘ arguments.

This table is then used with the translate() method to remove all punctuation characters from the ‘text’ string in Python, resulting in ‘cleaned_text.

Output

Cleaned Text: hello world

Here’s a screenshot showcasing my Python code in Visual Studio.

Replace multiple characters at once in python string

How to replace multiple characters in a string in Python using re.sub() method

We use re.sub(), a built-in method of re module in Python. This method offers a versatile solution to replace multiple characters in a string based on specified patterns.

Let’s illustrate the use of the re.sub() to replace multiple characters in a string in Python:

Code

import re

text = "The price is $1,234.56 and it's 20% off!"
cleaned_text = re.sub(r'[$,%!]', "", text)
print("Cleaned Text:", cleaned_text)

In this example, we are trying to replace all occurrences of characters ‘$’, ‘,’, ‘%’, and ‘!‘ from the ‘text‘ string.

Output

Cleaned Text: The price is 1234.56 and it's 20 off

Included is a screenshot displaying my Python code from Visual Studio.

Replace Character in a String of Python

Replacing multiple characters in a string using list comprehension in Python

List comprehension offers a concise and efficient method to replace multiple characters in a string in Python based on specified mappings.

Here is an instance:

Code

text = "I love Python programming"
replacements = {"o": "0", "g": "9", "m": "M"}

modified_text = ''.join([replacements[char] if char in replacements else char for char in text])
print("Modified Text:", modified_text)

In this example, a list comprehension is used to iterate over each character in the ‘text’ string to replace multiple characters in a string in Python.

''.join([replacements[char] if char in replacements else char for char in text])

For each character, the expression checks if the character exists in the ‘replacements‘ dictionary in Python.

READ:  How to Capitalize Alternate Letters in a String in Python [8 Ways]

Output

Modified Text: I l0ve Pyth0n pr09raMMin9

Here’s a screenshot of my Python code running in Visual Studio.

Python Replace Multiple Characters in string

Python replace multiple characters from a string using a dictionary.

Using a dictionary to map characters to their replacements provides a flexible and efficient approach for replacing multiple characters in a string in Python based on predefined mappings.

Here is an instance to do:

Code

text = "CA is short for California, and NY stands for New York"

state_abbreviations = {"CA": "California", "NY": "New York"}

modified_text = ''.join(state_abbreviations.get(text[i:i+2], text[i:i+2]) for i in range(0, len(text), 2))
print("Modified Text:", modified_text)

In this example, a dictionary named ‘state_abbreviations’ is defined, where each key-value pair represents an abbreviation and its corresponding full name.

''.join(state_abbreviations.get(text[i:i+2], text[i:i+2]) for i in range(0, len(text), 2))

The code iterates over the ‘text‘ string in steps of two characters using a range, and for each pair of characters, it checks if they exist as a key in the ‘state_abbreviations‘ dictionary in Python.

Output

Modified Text: California is short for California, and New York stands for New York

Attached is a screenshot of my Python code in Visual Studio.

Replacing Multiple Characters in a String with Python

Replace characters in a Python string using the re.subn() function

In Python, the re.subn() function is a built-in method provided by the re module, which performs substitutions in strings based on regular expression patterns.

This function searches for all occurrences of the specified pattern in the given string and can replace multiple characters in a string.

Code

import re

email = "john.doe@example.com"
cleaned_email, _ = re.subn(r'\.\w+@', "@", email)
print("Cleaned Email:", cleaned_email)

Output

Cleaned Email: john@example.com

Presented is a screenshot showing my Python code in Visual Studio.

Using Python to Replace Characters in a String

Replace Character in a String using a list of replacements with for loop

The for loop is used for iterating over a list of replacement tuples containing pairs of characters to be replaced and their corresponding replacements in Python.

READ:  12 Ways to check if Python String contains Substring

For each pair in the ‘replacements’ list, the code checks if the character to be replaced exists in the input string.

Code

string = 'jack!doe_gmail.com'

replacements = [('!', ''), ('_', '@')]

for char, replacement in replacements:
    if char in string:
        string = string.replace(char, replacement)

print(string)

In this code snippet, the input string ‘jack!doe_gmail.com’ contains characters ‘!’ and ” that must be replaced with ‘‘ (empty string) and ‘@’, respectively.

The Python list of replacements is defined as [(‘!’, ”), (”, ‘@’)].

Output

jackdoe@gmail.com

Shown here is a screenshot capturing my Python code in Visual Studio.

Replacing Multiple Characters Simultaneously in Python

Conclusion

You can see seven methods to replace multiple characters in a string in Python. We’ve covered techniques like using nested replace() and translate() methods and also used regular expressions with re.sub() and re.subn(), etc, in detail with examples.

By understanding and utilizing these methods, developers can effectively manipulate strings to suit their needs in various real-world scenarios.

You may also like to read these Python articles: