Python

Python Menu

Python

Python String maketrans() - Definition, Syntax, Parameters, Examples

Definition

The maketrans() method returns a mapping table that can be used with the translate() method to replace specified characters.

Syntax

string.maketrans(x, y, z)

Parameters

Parameter Description
x Required. If only one parameter is specified, this has to be a dictionary describing how to perform the replace. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace.
y Optional. A string with the same length as parameter x. Each character in the first parameter will be replaced with the corresponding character in this string.
z Optional. A string describing which characters to remove from the original string.

Examples:

mytxt = "Hello World!" mytable = mytxt.maketrans("W", "P") print(mytxt.translate(mytable)) # with 2 parameters mytxt = "Hi Sam!" x = "mSa" y = "eJo" mytable = mytxt.maketrans(x, y) print(mytxt.translate(mytable)) # with 3 parameters mytxt = "Good night Sam!" x = "mSa" y = "eJo" z = "odnght" mytable = mytxt.maketrans(x, y, z) print(mytxt.translate(mytable))

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods