我有一个函数的代码部分,用于替换字符串中编码错误的外来字符:
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"
我在这里需要一个“真正的”字符串,而不是字节。但是当我想解码它们时,我有一个异常(exception):
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'
提前致谢 !
编辑:
python3中的pypyodbc默认使用所有unicode。这让我很困惑。在连接时,您可以告诉他使用 ANSI。
con_odbc = pypyodbc.connect("DSN=GP", False, False, 0, False)
然后,我可以将返回的东西转换为cp850,这是数据库的初始代码页。
str(odbc_str, "cp850", "replace")
不再需要手动替换每个特殊字符。
非常感谢pepr
最佳答案
打印b"String from an old database with weird mixed encodings"
不是字符串内容的表示。它是字符串内容的值。由于您没有将编码参数传递给 str()
...(见文档 https://docs.python.org/3.4/library/stdtypes.html#str)
If neither encoding nor errors is given,
str(object)
returnsobject.__str__()
, which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a__str__()
method, thenstr()
falls back to returningrepr(object)
.
这就是你的情况。
b"
实际上是两个字符,它们是字符串内容的一部分。你也可以试试:s1 = 'String from an old database with weird mixed encodings'
print(type(s1), repr(s1))
by = bytes(s1, 'cp1252')
print(type(by), repr(by))
s2 = str(by)
print(type(s2), repr(s2))
它打印:
<class 'str'> 'String from an old database with weird mixed encodings'
<class 'bytes'> b'String from an old database with weird mixed encodings'
<class 'str'> "b'String from an old database with weird mixed encodings'"
这就是为什么
s[2:][:-1]
的原因为你工作。如果你想多了,那么(在我看来)或者你想得到
bytes
或 bytearray
从数据库(如果可能),并修复字节(请参阅 bytes.translate https://docs.python.org/3.4/library/stdtypes.html?highlight=translate#bytes.translate )或您成功获得字符串(幸运的是,构造该字符串时没有异常(exception)),并且您想替换错误的字符通过正确的字符(另见 str.translate()
https://docs.python.org/3.4/library/stdtypes.html?highlight=translate#str.translate )。可能是 ODBC 在内部使用了错误的编码。 (即数据库的内容可能是正确的,但它被 ODBC 误解了,您无法告诉 ODBC 什么是正确的编码。)然后您想使用该错误编码将字符串编码回字节,然后使用正确的编码对字节进行解码。
关于python-3.x - python 3.4 : str : AttributeError: 'str' object has no attribute 'decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26014209/