When and why to use the former instead of the latter and vice versa?
It is not entirely clear why some use the former and why some use the latter.
The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. Use the maketrans() method to create a mapping table. If a character is not specified in the dictionary/table, the character will not be replaced.
The replace() method returns a copy of the string where the old substring is replaced with the new substring.
The string translate() method returns a string where each character is mapped to its corresponding character in the translation table. translate() method takes the translation table to replace/translate characters in the given string as per the mapping table.
They serve different purposes.
translate
can only replace single characters with arbitrary strings, but a single call can perform multiple replacements. Its argument is a special table that maps single characters to arbitrary strings.
replace
can only replace a single string, but that string can have arbitrary length.
>>> table = str.maketrans({'f': 'b', 'o': 'r'})
>>> table
{102: 'b', 111: 'r'}
>>> 'foo'.translate(table)
'brr'
>>> 'foo'.translate(str.maketrans({'fo': 'ff'}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string keys in translate table must be of length 1
>>> 'foo'.replace('fo', 'ff')
'ffo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With