DEV Community

Aravind R
Aravind R

Posted on

TIL#1 - translate() & str.maketrans()

translate()

translate() is a string method used to obtain a new string where specified characters are replaced by others based on a mapping table or dictionary.

  • For mapping, the dictionary can be user defined or a mapping table can be made using str.maketrans() method.

  • While defining a dictionary to use for mapping, the keys and values should be ascii values of the characters to be replaced.
    Eg: To replace "a" with "z" the dictionary should be {97:122}

  • To remove a character, assign its value as **None **in the dictionary.

Syntax:
    -stringName-.translate(-dictionary-)
Enter fullscreen mode Exit fullscreen mode

str.maketrans()

str.maketrans() creates a mapping table that can be used in translate(). It takes 2 strings as arguments. string 1 contains the characters to be replaced and string 2 contains the characters that replace them.

  • The position of characters in both strings should be in the order of replacement. 1st character of string 1 will be replaced by 1st character in string 2 and so on.

  • The mapping table is composed of ascii numbers of individual characters as key-value pairs. It cannot map whole words for replacement.

  • A 3rd string can be given as an optional argument. Characters in this string will be mapped to None, and will be removed from the returned string.

Syntax:
    str.maketrans(-string1-, -string2-, -stringOptional-)
Enter fullscreen mode Exit fullscreen mode

That's about it. Any additions or corrections would be appreciated.
Happy Learning :-)

Top comments (0)