Python String translate() Method
The Python translate() method converts the characters of a string based on the table given by the argument table (which contains 256 characters), and puts the characters to be filtered out in the deletechars argument.
Python String translate() Syntax
translate() method syntax.
str.translate(table)
bytes.translate(table[, delete])
bytearray.translate(table[, delete])
Python String translate() Parameters
- table – translation table, the translation table is converted by maketrans() method.
- deletechars – The list of characters to be filtered in the string.
Python String translate() Return Value
The translated string is returned, and if the delete parameter is given, the characters belonging to delete are removed from the original bytes, and the remaining characters are mapped according to the mapping given in the table.
Python String translate() Example#1
The following example demonstrates the use of the translate() function.
#!/usr/bin/python3
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) # Making translation sheets
str = "this is string example....from apidemos.com"
print (str.translate(trantab))
Output:
Python String translate() Example#2
The following example demonstrates how to filter out the character o.
#!/usr/bin/python
# Making translation sheets
bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
# Convert to uppercase and delete the letter o
print(b'apidemos'.translate(bytes_tabtrans, b'o'))
Output: