【问题标题】:translate with empty string用空字符串翻译
【发布时间】:2013-07-18 03:18:23
【问题描述】:

这是来自another answer 的示例,它仅提取小写字母。 (Python 3)

import string
delete_table = string.maketrans(
    string.ascii_lowercase, ' ' * len(string.ascii_lowercase)
)
table = string.maketrans('', '')

"Agh#$%#%2341- -!zdrkfd".translate(table, delete_table)

在这种情况下,' ' * len(string.ascii_lowercase) 将小写字母映射到空格。所以我的期望是所有的小写字母都将被替换为'',一个空格,但这是输出:

'ghzdrkfd'

所以这是我的问题:

  1. 为什么输出与我的预期不同?
  2. 当我查看documentation 时,translate 只接受一个参数。为什么要传递两个参数?

【问题讨论】:

    标签: python syntax


    【解决方案1】:

    您已链接到 Python 3.x 文档,但如果 translate() 与多个参数一起使用,则此代码可能来自有效的 Python 2.x。这是documentation

    如您所见,第二个参数是可选的,它指定应从输入字符串中删除的字符(在 Python 3.x 上,您可以通过将字符映射到 None 来执行此操作)。

    所以对于"Agh#$%#%2341- -!zdrkfd".translate(table, delete_table),首先删除delete_table 中存在的所有字符,然后使用table 执行翻译。

    由于delete_table 是使用string.maketrans() 将所有小写字母转换为空格来构造的,因此它将是一个包含除小写字母之外的所有ASCII 字符的字符串:

    >>> delete_table = string.maketrans(string.ascii_lowercase, ' '*len(string.ascii_lowercase))
    >>> delete_table
    '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`                          {|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
    >>> ''.join(c for c in map(chr, range(0, 256)) if c not in delete_table)
    'abcdefghijklmnopqrstuvwxyz'
    

    因此所有其他字符将从字符串中删除,然后使用table 的翻译不会修改任何内容,因为使用了string.maketrans('', '')

    【讨论】:

      【解决方案2】:

      有一个translate() 的成员版本以及一个静态函数。具有一个参数的成员版本按您的预期工作,而我相信它是您在上面调用的静态版本,可能是错误的。

      >>> "Agh#$%#%2341- -!zdrkfd".translate(delete_table)
      'A  #$%#%2341- -!      '
      

      【讨论】:

        猜你喜欢
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 2013-08-29
        • 1970-01-01
        • 2020-01-20
        相关资源
        最近更新 更多