pythonstringmethodstranslate

Python maketrans() and translate() not working


Trying to utilize the Python string translate() and maketrans() methods for replacing a string. Yes, both strings are the same length. When I replace "Tuxedo" with "Serena"- it works. When I replace "Serena" with "Tuxedo"- I get "Texedo".

sailorsquad = str.maketrans("Serena","Tuxedo")
txt = "Serena"
txt.translate(sailorsquad)
'Texedo'
sailorsquad = str.maketrans("Tuxedo","Serena")
txt = "Tuxedo"
txt.translate(sailorsquad)
'Serena'

Also tried doing just txt.translate and it still does not work.


Solution

  • "Serena" has two e's, so when you you make a translation table from it with e -> u and e -> e, the last one wins:

    >>> str.maketrans("Serena","Tuxedo") == str.maketrans("Srena", "Txedo")
    True
    

    In other words, 'e' still maps to 'e' in that transalation table:

    >>> chr(str.maketrans("Serena","Tuxedo")[ord('e')])
    'e'
    

    The inverse, Tuxedo -> Serena works fine because the letters of "Tuxedo" are all unique.

    If you're actually trying to replace whole words and not individual characters, perhaps you just want to simply use str.replace instead:

    >>> "Hello Serena".replace("Serena", "Tuxedo")
    'Hello Tuxedo'