小编Rom*_*omu的帖子

Python 3.4:str:AttributeError:'str'对象没有属性'decode

我有一个函数的代码部分,从字符串中替换严重编码的外来字符:

s = "String from an old database with weird mixed encodings"
s = str(bytes(odbc_str.strip(), 'cp1252'))
s = s.replace('\\x82', 'é')
s = s.replace('\\x8a', 'è')
(...)
print(s)
# b"String from an old database with weird mixed encodings"
Run Code Online (Sandbox Code Playgroud)

我这里需要一个"真正的"字符串,而不是字节.但是,当我想解码它们时,我有一个例外:

s = "String from an old database with weird mixed encodings"
s = str(bytes(odbc_str.strip(), 'cp1252'))
s = s.replace('\\x82', 'é')
s = s.replace('\\x8a', 'è')
(...)
print(s.decode("utf-8"))
# AttributeError: 'str' object has no attribute 'decode'
Run Code Online (Sandbox Code Playgroud)
  • 你知道为什么s是字节吗?
  • 为什么我不能将它解码为真正的字符串?
  • 你知道怎么做干净的方式吗?(今天我回到s [2:] [: - 1].工作但非常难看,我想了解这种行为)

提前致谢 !

编辑: …

encoding bytestring python-3.x

7
推荐指数
1
解决办法
3万
查看次数

标签 统计

bytestring ×1

encoding ×1

python-3.x ×1