相关疑难解决方法(0)

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

通过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 …
Run Code Online (Sandbox Code Playgroud)

python string python-2.7

23
推荐指数
2
解决办法
3万
查看次数

标签 统计

python ×1

python-2.7 ×1

string ×1