str.translate Translating characters in a string

suggest change

Python 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'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents