str.translate vs str.replace – When to use which one?

Question:

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.

Asked By: Outcast

||

Answers:

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'
Answered By: chepner
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.