python maketrans 字典_python3中maketrans()方法的使用

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.maketrans(x[,y[,z]])可返回用于str.translate()的转换表

如果只有一个参数,必须是一个字典

例:str.maketrans(x)

>>> d = {'a':'1','b':'2','c':'3','d':'4','e':'5','s':'6'}

>>> trantab = str.maketrans(d)

>>> st='just do it'

>>> print(st.translate(trantab))

'ju6t 4o it'

>>> d = {'a':'123','s':'456','d':'789'}

>>> trantab = str.maketrans(d)

>>> st='just do it'

>>> print(st.translate(trantab))

ju456t 789o it

>>> d = {'a':'123','s':'456','d':None}

>>> trantab = str.maketrans(d)

>>> st='just do it'

>>> print(st.translate(trantab))

ju456t o it

如果两个参数,x,y长度必须是相等的字符串,x中每个字符将映射到y中相同位置的字符

例:str.maketrans(x,y)

>>> x = 'abcdefs'

>>> y = '1234567'

>>> st='just do it'

>>> trantab = str.maketrans(x,y)

>>> print(st.translate(trantab))

ju7t 4o it

如果三个参数,第三个参数必须是个字符串,其字符将被映射为None

例:str.maketrans(x,y,z)

>>> x = 'abcdefs'

>>> y='1234567'

>>> z='ot'

>>> st='just do it'

>>> trantab = str.maketrans(x,y,z)

>>> print(st.translate(trantab))

ju7 4 i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值