How to Use String maketrans() Method in PythonPython Basics


The maketrans() method creates a conversion table for character mapping. It maps each character in one string into the character at the same position in another string.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

intab = "this!"
outtab = "THIS?"
trantab = str.maketrans(intab, outtab)

str = "this is a example...!!!"
print(str.translate(trantab))

Output:

THIS IS a example...???

Syntax

str.maketrans(intab, outtab)

Parameters

Name Description
intab A sequence of characters to be replaced in a string
outtab A sequence of corresponding mapped characters

Return Value

It returns a translation table with 1-to-1 mapping of each character to its translation.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us