str_update=str_input.maketrans(str_search,str_replace,str_delete)
str_search : Required, Chars to be searchedstr_replace: Required, Chars to be replaced ( mapped to searched chars )str_delete : Optional, Chars to be replaced with None ( deleted in final string )
str_search='abc' # search chars
str_replace='xyz' # replace chars
str_delete='pqr' # delete chars
str_input='abcdefghpqr' #input string
str_update=str_input.maketrans(str_search,str_replace,str_delete)
print(str_update) # dictionary output with chars mapped.
print("input string : ",str_input)
print("Output string: ",str_input.translate(str_update))
Output
{97: 120, 98: 121, 99: 122, 112: None, 113: None, 114: None}
input string : abcdefghpqr
Output string: xyzdefgh
str.translate(translation_table)
str_input = "abcdef"
table = str.maketrans("abc", "xyz")
print(str_input.translate(table))
Output:
xyzdef
str_input = "hello world!"
table = str.maketrans("", "", "aeiou")
print(str_input.translate(table))
Output:
hll wrld!
str_input = "apple pie"
table = str.maketrans("ap", "xy", "e")
print(str_input.translate(table))
Output:
xyyl yi
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.