Wonderful String Translation Function in Python / Python神奇的字符串变换函数

来源:互联网 发布:一带一路的进展 知乎 编辑:程序博客网 时间:2024/05/08 18:12

So wonderful is the translation function in python, which seems to be deliberately designed for ascii encoding/decoding games...

the function of [string].translate([rule]) is translating the [string] into a certain string following the given [rule].

The [rule] is a string conprising exactly 256 characters indicating the corresponding objective character for each origin character ranged 0..255.

e.g. a rule string r, within values of r[65]='A', r[66]='2', etc., means the character of ascii 65 ('a'), should be converted into 'A', and the one of ascii 66('b') should be converted into '2';

You may think it boring to make up such a string artificially, for programmers are required to provide not only the mapping rule for the characters we want to translate but also the ones we don't care. It's especially dull to type in the invisible characters for the 256-chars-long string. 

There's a function in string library helps you do this: string.maketrans([origin], [object])(Before using it you must import string first)

For example, if you want to translate all 'a's in a string to 'A' and all 'd's to '4' remaining all other characters unchanging, the rule_string = string.maketrans("da", "4A").

 

A complete example for the two functions' usage, it shift all the lowercase letters by 2 chars('a'->'c', 'b'->'d',..):

import string

a = "GlgkNgw qywq qrpgle.rpylqjyrc() gq y sqcdsj rmmj."

trans = string.maketrans("abcdefghijklmnopqrstuvwxyz", "cdefghijklmnopqrstuvwxyzab")
print a.translate(trans)

 
原创粉丝点击