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)
本文深入探讨了Python中字符串转换的功能,特别是[string].translate([rule])函数的使用方法。该函数可以按照指定规则对字符串进行转换,规则字符串由256个字符组成,对应ASCII码表中的每个字符。文章还介绍了如何利用string库中的maketrans函数简化规则字符串的创建过程。
3460

被折叠的 条评论
为什么被折叠?



