Skip to content

Python replace multiple characters in string | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading