【发布时间】:2014-01-29 02:32:32
【问题描述】:
通过string.translate 函数显示:
从 s 中删除 deletechars 中的所有字符(如果存在),然后使用 table 翻译字符,table 必须是一个 256 字符的字符串,给出每个字符值的翻译,按其序号索引。如果 table 为 None,则只执行字符删除步骤。
-
table 在这里是什么意思?可以是包含映射的
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
>>> "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
>>> "abc".translate({"a": "d", "c": "x"}, ["b"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
我在这里错过了什么?
【问题讨论】:
标签: python string python-2.7