str.translate Translating characters in a string
suggest changePython supports a translate method on the str type. It takes one argument, a translation table. str.maketrans builds that table, including characters that should be deleted.
str.translate(table)
table maps Unicode ordinals to ordinals, strings, or None.
>>> translation_table = str.maketrans("aeiou", "12345")
>>> my_string = "This is a string!"
>>> translated = my_string.translate(translation_table)
'Th3s 3s 1 str3ng!'
The translate method returns a string which is a translated copy of the original string.
To delete characters, map them to None. The third argument of str.maketrans does that:
>>> 'this syntax is very useful'.translate(str.maketrans('', '', 'aeiou'))
'ths syntx s vry sfl'
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents