string.translate函数中的"table"是什么意思?

Ble*_*ers 23 python string python-2.7

通过string.translate功能说:

删除deletechars中的所有字符(如果存在),然后使用表转换字符,该表必须是256个字符的字符串,为每个字符值提供转换,并按其序号索引.如果table为None,则仅执行字符删除步骤.

  • 是什么意思?它可以dict包含映射吗?
  • 什么是"必须是256个字符的字符串"是什么意思?
  • 可以在表中可以手动或通过自定义函数,而不是做string.maketrans

我尝试使用该功能(尝试下面)只是为了看它是如何工作但是没能成功使用它.

>>> "abcabc".translate("abcabc",{ord("a"): "d", ord("c"): "x"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: translation table must be 256 characters long
Run Code Online (Sandbox Code Playgroud)
>>> "abcabc".translate({ord("a"): ord("d"), ord("c"): ord("x")}, "b")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
Run Code Online (Sandbox Code Playgroud)

>>> "abc".translate({"a": "d", "c": "x"}, ["b"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

fal*_*tru 22

这取决于您使用的Python版本.

在Python 2.x. 该表是256个字符的字符串.它可以使用string.maketrans以下方法创建:

>>> import string
>>> tbl = string.maketrans('ac', 'dx')
>>> "abcabc".translate(tbl)
'dbxdbx'
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,表是unicode序列到unicode字符的映射.

>>> "abcabc".translate({ord('a'): 'd', ord('c'): 'x'})
'dbxdbx'
Run Code Online (Sandbox Code Playgroud)

  • Python 2`unicode.translate()`的行为与Python 3中的`str.translate()`完全相同.那是因为你有超过256种可能的值要翻译.相反,`bytes.translate()`的工作方式与Python 2`str.translate()`完全相同.所以它不依赖于Python版本,它取决于对象类型; Unicode vs bytestring. (4认同)

Mar*_*ers 10

table必须是256个字符的字符串; 该str.translate()方法使用此表将字节值(0到255之间的数字)映射到新字符; 例如,任何字符'a'(具有整数值97的字节)将替换为表中的第98个字符.

你真的想要参考所有这些的str.translate()文档,而不是string.translate()函数; 后一种文件并不完整.

你可以使用string.maketrans函数构建一个; 你只需要用替换它们的字符替换你想要替换的字符; 对于你的例子,那是:

>>> import string
>>> table = string.maketrans('ac', 'cx')
>>> len(table)
256
>>> table[97]
'c'
>>> 'abcabc'.translate(table, 'b')
'cxcx'
Run Code Online (Sandbox Code Playgroud)

第二个参数也应该是一个字符串.

您似乎已阅读该unicode.translate()方法的文档; 行为改变了,你确实必须传入字典unicode.translate().由于Python 2 unicode类型是strPython 3中的类型,因此您也可以str.translate()在Python 3中使用它(bytes.translate()与上述行为相匹配).