Forem

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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay