【发布时间】:2010-06-07 17:22:16
【问题描述】:
我有包含字符 "\x80" 的 ascii 字符串来表示欧元符号:
>>> print "\x80"
€
将包含此字符的字符串数据插入我的数据库时,我得到:
psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x80
HINT: This error can also happen if the byte sequence does not match the encodi
ng expected by the server, which is controlled by "client_encoding".
我是 unicode 新手。如何将包含 "\x80" 的字符串转换为包含相同欧元符号的有效 UTF-8?我尝试在各种字符串上调用.encode 和.decode,但遇到了错误:
>>> "\x80".encode("utf-8")
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
"\x80".encode("utf-8")
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128)
【问题讨论】:
-
您必须从当前语言环境(
\x80==€)对其进行 .decode(),然后 .encode("utf-8") -
如果你有一个 ASCII 字符串,你就没有 "\x80"。相反,如果你有 "\x80",你就没有 ASCII 字符串。
-
@Thanatos:是的。正如我所说,我是一个字符编码新手,我不知道还能叫什么。我只是说前面没有“u”的python字符串文字。
标签: python postgresql unicode encoding utf-8