Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 505
Outcast Avatar asked May 30 '19 12:05

Outcast


People also ask

What does translate () do Python?

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.

What does str replace do in Python?

The replace() method returns a copy of the string where the old substring is replaced with the new substring.

What is string translate?

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.


1 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'
like image 69
chepner Avatar answered Oct 07 '22 18:10

chepner