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).
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_string = "Hello world" replace_char = ["e", "w"] for char in replace_char: a_string = a_string.replace(char, "Z") print(a_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)
Do comment if you have any doubts and suggestions on this Python char string topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.