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