您的位置:首页 > 编程语言 > Python开发

Python 3.x 字符串的makestrans函数和translate方法使用详解

2013-11-20 14:43 1626 查看
使用字符串的makestrans函数和translate方法可用来进行快速编码。

先看一下官方说明

staticstr.maketrans(x[,y[,z]])
This static method returns a translation table usable for
str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be
mapped to None in the result.

该静态函数返回可用于str.translate()方法的转换表。

如果只有一个参数,它必须是dict类型,键key为长度为1的字符(unicode字符码或者字符),值value为任意长度字符串或者None。键key对应的字符将被转换为值value对应的字符(串)。

如果有两个参数,他们长度必须相等,每一个x字符将被转换为对应的y字符。如果有第三个参数,其对应的字符将被转换为None。

str.translate(map)
Return a copy of the s where all characters have been mapped through themap which must be a dictionary of Unicode ordinals (integers) to Unicode ordinals, strings orNone. Unmapped characters are left
untouched. Characters mapped toNone are deleted.

You can use
str.maketrans() to create a translation map from character-to-character mappings in different formats.

返回一个使用参数map转换后的字符串,map必须是一个unicode字符码(整形)到unicode字符,字符串或None的映射表,未被映射的字符保持不表,被映射为None的字符将被删除。

可以使用str.maketrans()来创建转换表。

举例说明:

1)使用一个dict参数,创建字符到字符的转换表

>>> s = 'abcxyz123'
>>> m = {'a':'A', 'b':'B'} #用于创建一个'a' -> 'A', 'b' -> 'B' 的转换表
>>> trans = str.maketrans(m)
>>> s.translate(trans)
'ABcxyz123'


2)使用一个dict参数,创建一个字符到多个字符的转换表

>>> s = 'abcxyz123'

>>> m = {'a':'AAA', 'b':'BB'}
#用于创建一个'a' -> 'AAA', 'b' -> 'BB'的转换表

>>> trans = str.maketrans(m)

>>> s.translate(trans)

'AAABBcxyz123'



3)使用一个dict参数,创建字符到None的转换表(用于过滤要删除的字符)

>>> s = 'abcxyz123'
>>> m = {'a':None, 'b':None} #用于创建一个删除'a', 'b'的转换表
>>> trans = str.maketrans(m)
>>> s.translate(trans)
'cxyz123'


4)使用两个参数,创建字符到字符的转换表

>>> s = 'abcxyz123'
>>> trans = str.maketrans('abc', 'ABC')
>>> s.translate(trans)
'ABCxyz123'


5)使用三个参数,创建字符到字符的转换表,并同时包含要过滤删除的字符表

>>> s = 'abcxyz123'
>>> trans = str.maketrans('abc', 'ABC', '123456')
>>> s.translate(trans)
'ABCxyz'


6)使用unicode字符的情况

>>> hex(ord('我'))
'0x6211'
>>> hex(ord('你'))
'0x4f60'
>>> hex(ord('兵'))
'0x5175'

>>> s = '我是一个兵!'
>>> m = {'\u6211':'\u4f60', '\u5175':'流氓'}
>>> trans = str.maketrans(m)
>>> s.translate(trans)
'你是一个流氓!'


参考cookbook,对translate进行简单封装

>>> def translator(frm='', to='', delete=''):
if len(to) == 1:
to = to * len(frm) #eg. from:'12345678' to:'#'
trans = str.maketrans(frm, to, delete)
def translate(s):
return s.translate(trans)
return translate

>>> s = 'abcxyz123'
>>> trans = translator('abc', 'ABC', '123')
>>> trans(s)
'ABCxyz'
>>> trans = translator('1234567890', '#')
>>> trans(s)
'abcxyz###'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: