Python replace multiple characters in string | Example code

Use replace() method with a for-in loop to replace multiple characters in a string in Python programming. There is also another way to do it like Using nested replace() or translate() + maketrans() methods (Support only Python 2).

str.replace(old, new) 

Example Python replace multiple characters in a string

Simple example code replacing multiple characters in a string creates a new string with the replaced characters.

A for-loop needed to iterate over a list of characters to replace. Replacing the list of char with “Z“.

a_string = "Hello world"

replace_char = ["e", "w"]

for char in replace_char:
    a_string = a_string.replace(char, "Z")

print(a_string)

Output:

Python replace multiple characters in string

Using translate() + maketrans()

Works only in Python2.

import string

test_str = "aaa bb cc"

res = test_str.translate(string.maketrans("a", "b"))

print(res)

Replace multiple characters in a string at once

Replace vowels with space, where a string is given by the user.

string = input('Enter something to change: ')
vowels = 'aeiouy'

for i in vowels:
    string = string.replace(i, ' ')

print(string)

Output:

Replace multiple characters in a string at once

Do comment if you have any doubts and suggestions on this Python char string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.