Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python translate() method

Python translate() method

Python Strings Python Strings


Description

The Python translate() method converts the characters of a string according to a table (containing 256 characters) given by the table parameter; characters to be filtered out are placed in the del parameter.

Syntax

Syntax of the translate() method:


str.translate(table[, deletechars]);

Parameters

Return Value

Returns the translated string.

Example

The following example shows how to use the translate() function:

Example (Python 2.0+)

#!/usr/bin/python

from

string

import

maketrans

Reference the maketrans function.

intab

=

"

aeiou

"

outtab

=

"

12345

"

trantab

=

maketrans

(

intab

,

outtab

)

str

=

"

this is string example....wow!!!

"

;

print

str

.

translate

(

trantab

)

;

The output of the above example is:


th3s 3s str3ng 2x1mpl2....w4w!!!

The above example removes the 'x' and 'm' characters from the string:

Example (Python 2.0+)

#!/usr/bin/python

from

string

import

maketrans

Required to call maketrans function.

intab

=

"

aeiou

"

outtab

=

"

12345

"

trantab

=

maketrans

(

intab

,

outtab

)

str

=

"

this is string example....wow!!!

"

;

print

str

.

translate

(

trantab

,

'

xm

'

)

;

The example above produces the following output:


th3s 3s str3ng 21pl2....w4w!!!

Python Strings Python Strings