为什么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]
答案 0 :(得分:0)
来自documentation(强调我的):
string.translate(s, table[, deletechars])
删除
deletechars
中的所有字符(如果存在),然后使用table
,翻译字符,该字符必须是256个字符的字符串,为每个字符提供翻译价值,按其序数索引。
在您的代码中,remap
无法满足此要求。