【发布时间】:2015-03-05 20:42:26
【问题描述】:
为什么使用字典时 translate() 会给我TypeError: expected a character buffer object 错误?
remap = {
'with': 'TEXT1',
'as': 'TEXT2',
'text_in': 'TEXT3'
}
s = "with open(loc_path + 'sample_text.txt', 'rb') as text_in:"
ss = s.translate(remap)
print ss
这是错误信息:
Traceback (most recent call last):
File "C:\...\REMAP1.py", line 9, in <module>
ss = s.translate(remap)
TypeError: expected a character buffer object
[Finished in 0.1s with exit code 1]
使用 replace() 有效:
#ss = s.translate(remap)
#print ss
s = s.replace('with', 'TEXT1')
s = s.replace('as', 'TEXT2')
s = s.replace('text_in', 'TEXT3')
print s
输出:
TEXT1 open(loc_path + 'sample_text.txt', 'rb') TEXT2 TEXT3:
[Finished in 0.1s]
【问题讨论】:
-
是什么让您认为
translate可以这样使用?你读过the documentation吗? -
你想投反对票吗?它在 python 食谱中以这种方式使用,所以我想看看它是否有效。
-
@jes516:包含无效代码的 Python 食谱?不要再使用它了。