[Python learning] Text Processing-translate

Source: Internet
Author: User
Tags translate function

2011-09-15

Look at the cookbook and see the amazing string. translate function.

You can remove unnecessary strings from the string and map some characters into other characters by using the maketrans ing function.
Cookbook encapsulates the translate code to create a new facade function:

import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
allchars = string.maketrans('', '')
delete = allchars.translate(allchars, keep.translate(allchars, delete))
def translate(s):
return s.translate(trans, delete)

Return translate >>> digits_only = translator (keep = string. digits)
>>> Digits_only ('chris Perkins: 224-7992 ')
'123'

What's really amazing is that I printed the string. maketrans (frm, to) value, and the results were blank. I haven't figured out how to complete the ing for a long time?

Enter lib/string. py can only see the source code. The maketrans returns a bytes string instead of an empty string when the from to is empty. In windows, nothing can be printed, I followed for a long time. In linux, you can see the complete value of the string, English character numbers and symbols.

Trans = string. maketrans (frm, to) obtains the original 256-byte string, finds the difference set between the keep and delete as the reserved value, finally obtains the string to be retained, and interprets the original string as the required value.

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.