python使用字典for translate()得到了“TypeError:expected a character buffer object”

2024-09-27 22:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么在使用字典时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

以下是错误消息:

^{pr2}$

使用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]

Tags: textinas错误withopenssloc
1条回答
网友
1楼 · 发布于 2024-09-27 22:20:09

来自documentation(重点矿):

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal.

在您的代码中,remap不满足此要求。在

相关问题 更多 >

    热门问题