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 :-)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️