Python Translate () method

Source: Internet
Author: User

Describe

The translate () method converts the character of a string according to the table given by the parameter table (containing 256 characters), and the character to be filtered out is placed in the deletechars parameter.

Grammar

Translate () method syntax:

Str.translate (table[, Deletechars]); Bytes.translate (table[, delete])    bytearray.translate (table[, delete])
Parameters
    • Table-translation tables, translation tables are converted through the Maketrans () method.
    • Deletechars--a list of characters to filter in the string.
return value

Returns the translated string, and if the delete parameter is given, the delete character in the original bytes is deleted, and the remaining characters are mapped according to the mappings given in the table.

Instance

The following example shows how the translate () function is used:

#!/usr/bin/python3 intab = "Aeiou" Outtab = "12345" Trantab = Str.maketrans (Intab, Outtab)   # make translation table str = "This is string EXAMPLE....WOW!!! " Print (Str.translate (trantab))

The result of the above example output is as follows:

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

The following example shows how to filter out the characters x and M:

#!/usr/bin/python # making translation Table Bytes_tabtrans = Bytes.maketrans (b ' abcdefghijklmnopqrstuvwxyz ', B ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ') # converts to uppercase and removes the letter oprint (b ' runoob '. Translate (Bytes_tabtrans, b ' o '))

The result of the above example output:

B ' Runb '

Python Translate () method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.