python3 translate_python3 字符串的 maketrans,translate 方法详解

字符串的translate, maketrans方法让人很迷惑,这里根据官方的__doc__研究了一下,限于英文水平,有些词译得可能

不太准确,欢迎交流!

Static methods defined here:

|

| maketrans(x, y=None, z=None, /)

| Return a translation table usable for str.translate().

|

| If there is only one argument, it must be a dictionary mapping Unicode

| ordinals (integers) or characters to Unicode ordinals, strings or None.

| Character keys will be then 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.

translate(...)

| S.translate(table) -> str

|

| Return a copy of the string S in which each character has been mapped

| through the given translation table. The table must implement

| lookup/indexing via __getitem__, for instance a dictionary or list,

| mapping Unicode ordinals to Unicode ordinals, strings, or None. If

| this operation raises LookupError, the character is left untouched.

| Characters mapped to None are deleted.

(x,y=None,z=None)如果只有x一个参数,那么它必须是一个字典,可以是unicode到字符,字符到unicode,字符串,

或者None, 并且key会转成系数,如'a'的unicode会转成97

''.maketrans({'a':'b'})

Out[30]:

{97: 'b'}

''.maketrans({'c':97})

Out[37]:

{99: 97}

其实这里转成字符对应的系数没什么作用,看下面的例子:

table = ''.maketrans({'t':97})

s = 'this is a test'

s.translate(table)

Out[43]:

'ahis is a aesa'

table = ''.maketrans({97:'t'})

s.translate(table)

Out[48]:

'this is 97 test'

看到没,还是只是完成了映射替换,并不会转成数字,也就是说只是在生成table时转换了(不知道为什么这么做,欢迎交流)

那如果目标字符串中有这个数字怎么办呢?

table = ''.maketrans({97:'t'})

s.translate(table)

Out[48]:

'this is 97 test'

可以看到,97并没有被替换

如是给了两个参数,x,y 必须是行长的字符串,结果会是字符,x,y中对应的位置形成映射,需要注意的是,

它并不是全字符串进行替换,你给定的字符串只反映了映射关系,并不能当作整体。它会一个一个的替换,看下面的例子:

s = 'this is a test'

table = ''.maketrans('is', 'it')

s.translate(table)

Out[54]:

'thit it a tett'

最后面的s也被替换了

再看一个:

s = 'this is a test'

table = ''.maketrans('test', 'joke')

s.translate(table)

Out[51]:

'ehik ik a eoke'

看到这里,你肯定又懵了,我去,t不应该映射成j吗,怎么成了e,那是因为这里有两个t,它应该是取的后面的一个

如果给了第三个参数,(第三个参数)它必须是字符串,这个字符串中的字符会被映射成None,简单点说就是删除了

s = 'this is a test'

table = ''.maketrans('is', 'mn','h')

s.translate(table)

Out[57]:

'tmn mn a tent'

很明显,第三个参数中的h 从最后结果中消失了,也就是删除了。总的来说translate是非常强大的,不仅能替换,还能删除。

那么这里还是有一个问题,当只给定一个参数时,字符虽然被成了系数(整数),最后并没有被替换,那如果我要替换数字怎么办?

s = 'this 996785433 9657576'

table = ''.maketrans('945', 'ABC')

s.translate(table)

Out[60]:

'this AA678CB33 A6C7C76'

可以看到,指定两个参数时,数字是可以正常 替换的。

所以,当指定一个参数时,是做不到这一点,因为只有一个参数时,字典的key长度只能为1.如果你替换数字,你至少得二个数字。

如有不妥,欢迎指正,交流。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值