How to use translate() and maketrans() to replace and remove multiple characters from string in Python

2 Answers

0 votes
s = "Python is an interpreted programming language"

# mapping_table()
# "aeiou" - characters to be replaced
# "AEIOU" - replacements characters
# "ag" - characters to be deleted

mapping_table = s.maketrans("aeiou", "AEIOU", "ag")

s = s.translate(mapping_table)

print(s)



'''
run:

PythOn Is n IntErprEtEd prOrmmIn lnUE

'''

 



answered Apr 15, 2021 by avibootz
0 votes
s = "Python is an interpreted programming language"
 
# mapping_table()
# "aeiou" - characters to be replaced
# "AEIOU" - replacements characters
# "ag" - characters to be deleted

mapping_dictionary = {'a': 'A', 'e':'E', 'i': 'I', 'o': 'O', 'u': 'U', 'a': None, 'g': None}
 
mapping_table = s.maketrans(mapping_dictionary)
 
s = s.translate(mapping_table)
 
print(s)
 
 
 
'''
run:
 
PythOn Is n IntErprEtEd prOrmmIn lnUE
 
'''

 



answered Apr 15, 2021 by avibootz
edited Apr 15, 2021 by avibootz
...