Python3 translate() method

Python3 字符串Python3 Strings


Description

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

Syntax

The syntax of the translate() method is:

str.translate(table)
bytes.translate(table[, delete])    
bytearray.translate(table[, delete]) 

Parameters

  • table -- translation table, which is converted via themaketrans()method.
  • deletechars -- the list of characters in the string to be filtered out.

Return Value

Returns the translated string. If the delete parameter is given, the characters belonging to delete in the original bytes are removed, and the remaining characters are mapped according to the mapping given in table.

Examples

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

Example (Python 3.0+)

#!/usr/bin/python3 intab = "aeiou" outtab = "12345" trantab = str.maketrans(intab, outtab) # Create a translation table str = "this is string example....wow!!!" print (str.translate(trantab))

The output of the above example is as follows:

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

The following example demonstrates how to filter out the character o:

Example (Python 3.0+)

#!/usr/bin/python # Create a translation table bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') # Convert to uppercase and remove the letter o print(b'example'.translate(bytes_tabtrans, b'o'))

The output of the above example is:

b'RUNB'

Python3 字符串Python3 Strings

Other Extensions