Ble*_*ers 23 python string python-2.7
通过string.translate
功能说:
删除deletechars中的所有字符(如果存在),然后使用表转换字符,该表必须是256个字符的字符串,为每个字符值提供转换,并按其序号索引.如果table为None,则仅执行字符删除步骤.
dict
包含映射吗?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)
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
类型是str
Python 3中的类型,因此您也可以str.translate()
在Python 3中使用它(bytes.translate()
与上述行为相匹配).
归档时间: |
|
查看次数: |
31384 次 |
最近记录: |