Python cookbook Version 2 (Chinese version [recipe 1.9]) Simplifies the usage of the string translate method

Source: Internet
Author: User
Recipe 1.9. Simplifying usage of strings 'translate Method
Recipe 1.9. Simplify the usage of the string translate method

Credit: Chris Perkins, Raymond hettinger

Problem

You often want to use the efficient string translate method, but it is difficult to remember this method and string. the detailed usage of the maketrans function, so you want a facade that can simplify its usage in general ).

Solution

As described in recipe 1.10, the string's translate method is very powerful and scalable. However, because of this powerful power and scalability, it seems necessary for us to use a "Facade" to add a front-end interface to it, to simplify its common usage:

Import string
Def Translator (FRM = '', To ='', delete = '', keep = none ):
If Len (to) = 1:
To = to * Len (FRM)
Trans = string. maketrans (FRM,)
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

Discussion

I often find that I want to use the string's translate method to do something, but every time I have to stop and think about its detailed usage (see recipe 1.10 for more details ). Therefore, I wrote a class myself (and then renamed it as factory closure, that is, the solution presented in the "solution" of this entry ), encapsulate multiple possible processes into a simple facade. Now, if I want a function to retain only the characters in the given set, I can simply construct and use this function:

>>> Digits_only = Translator (keep = string. digits)
>>> Digits_only ('chris Perkins: 224-7992 ')
'123'

To remove a character from a character set, it is also simple:

>>> No_digits = Translator (delete = string. digits)
>>> No_digits ('chris Perkins: 224-7992 ')
'Chris Perkins :-'

If you want to replace a character set with a single character set, you can do this:

>>> Digits_to_hash = Translator (from = string. digits, To = '#')
>>> Digits_to_hash ('chris Perkins: 224-7992 ')
'Chris Perkins :###-####'

Although the above usage may seem a little special, it is indeed a task that appears from time to time.

In this entry, I have to make a random design decision, that is, when the delete parameter overlaps with the keep parameter, let the delete parameter "eat" The keep parameter:

>>> Trans = Translator (delete = 'abc', keep = 'cdef ')
>>> Trans ('abcdefg ')
'Ef'

For your own applications, it is better to ignore Delete when keep is specified. If both are specified, it is best to throw an exception (because specifying both of them in the same translator call does not have much practical significance ). Similarly, as described in recipe 1.8 and recipe 1.10, the code in This entry applies only to common strings and does not apply to Unicode strings, because the Unicode string's translate method is different from the normal string (that is, the byte is the processing unit of the string) method of the same name.

---- Box begin ----
Closures

Closure is not so complex as to be terrible: it is just an "internal" function that refers to "The local name (variable) of the 'external' function containing the function )". The following is an example of Yang Chun:

Def make_adder (addend ):
Def adder (augend): Return augend + addend
Return Adder

Execute P = make_adder (23) to create a closure, that is, the internal function adder, which refers to a name bound to the value 23. Then, q = make_adder (42) creates another closure, and the addend in it is bound to the value 42. In this case, Q and Q do not interfere with each other. The two can coexist happily and independently. In this way, we can execute statements such as pprint P (100) and Q (100) and get the output with the Result 123 142.

In practice, you may often see that make_adder is regarded as closure, rather than being explained by the hard and lengthy "Return closure function" that is academic. Fortunately, the context is often clear about the specific situation. Calling make_adder a factory (or factory function, a factory function) is both accurate and refined; you can also say that it is a closure factory to clarify the fact that it is built and returns closures, instead of class or class instances.
---- Box e n d ----

See

Recipe 1.10 includes the translate (keep =...) in this entry ...) and more information about the translate method, as well as the equivalent scheme applicable to Unicode strings; documentation on the string translate method and the maketrans function in the string module in the library reference and python in a nutshell.

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.