Application of closures in python: usage of translate and maketrans, pythonmaketrans

Source: Internet
Author: User

Application of closures in python: usage of translate and maketrans, pythonmaketrans

Python is relatively efficient in processing strings, and there are many methods. The maketrans and translate methods are used in many cases. This article summarizes the usage of these two methods.

First, let's review the two methods:

① S. translate (table, str) removes the characters contained in str from string s. The remaining strings are replaced by the character ing relationship in table. A table can be interpreted as A conversion table. Compare 'a'-> 'A', 'B'-> 'B '.

② Tabel = string. maketrans ('s1 ', 's2') s1 and s2 must have the same length. maketrans generates a conversion table. If there is s1 in s, replace it with s2, this conversion table corresponds to each character and does not need to contain all the characters.

For example:

Import strings = 'helloworld, 0001111 'table = string. maketrans ('','') # No ing, keep the original string s. translate (table) # hello world, 00011s. translate (table, 'hello000) '# world, 1111 table = string. maketrans ('abcdefgh', 'abcdefgh') s. translate (table) # HEllo, worlD, 00011s. translate (table, 'World') # HEllo, 0001111

Now we can wrap makerans and translate to form a factory function that returns the closure (print is the factory function), as shown below:

import stringdef 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

Closure is used at the end of the function. Closure refers to the function that has the right to access the variables in another function scope. A common way to create a closure is to create another function within a function:

def make_adder(addend):   def adder(augend): return augend + addend   return adder

Execute p = make_addr (23) to generate a closure of the inner function addr. This closure references the name addend internally, and addend is bound to the value 23, and execute p (100) then 123 is returned.

Now we have closed all kinds of possibilities behind an interface we suggest using.

>>>digits_only = translator(keep = string.digits)>>>digits_only('Chris Perkins :224 -7992')'2247992'

Removing elements that belong to a character set is also very simple:

>>>no_digits = translator(delete = string.digits)>>>no_digits('Chris Perkins:224-7992')'Chris Perkings : - '

It can also be replaced:

>>>digits_to_hash = translator(from = string.digits, to = '#')>>>digits_to_hash('Chris Perkins :224-7992')'Chris Perkins: ###-####'

When there are overlapping parts of delete and keep, the delete parameter takes priority.

>>>trans = translator(delete = 'abcd', kepp ='cdef')>>>trans('abcdefg')'ef'

In fact, you can add some exceptions in more detail to handle the case of delete and keep at the same time.

I hope this article will help you with Python programming.


Usage of python3x translate

>>> A = 'Hello! World! '
>>> T = a. maketrans ('l', 'A ')
>>> A. translate (t)
'Heaao! Worad! '

>>> Ttt = a. maketrans ('lh ',' AB ')
>>> A. translate (ttt)
'Beaao! Worad! '

Translate is a one-to-one ing of characters. Each character will be replaced with the corresponding character whenever it appears.
Replace is a string replacement. After the string is complete, it is replaced as a whole. The length of the two string parameters of replace can be different.

How to pass an inner function to the outer layer in the python closure function?

Closures are not required to implement this function.

Def fun (callback, * x ):
Return callback (* x)

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.