How to Use String translate() Method in PythonPython Basics


The translate() method returns a string. In this string, each character is mapped to its corresponding character in the translation table.

Example

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

intab = "this!"
outtab = "THIS?"
trantab = str.maketrans(intab, outtab)  # make translation table

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

Output:

THIS IS an example....wow???

Syntax

string.translate(table)

Parameters

Name Description
table A translation table which contains the mapping between two characters.

Return Value

It returns a string where each character is mapped to its corresponding character as per the translation table.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us