我在编码 路径 变量并将其插入 SQLite 数据库时遇到问题。我尝试使用无帮助的 encode(“utf-8”) 函数来解决它。然后我使用了 unicode()
函数,它给了我类型 unicode 。
print type(path) # <type 'unicode'>
path = path.replace("one", "two") # <type 'str'>
path = path.encode("utf-8") # <type 'str'> strange
path = unicode(path) # <type 'unicode'>
最后我获得了 unicode 类型,但是当 路径 变量的类型为 str 时,我仍然遇到相同的错误
sqlite3.ProgrammingError:除非您使用可以解释 8 位字节串的 text_factory(如 text_factory = str),否则不得使用 8 位字节串。强烈建议您将应用程序切换为 Unicode 字符串。
你能帮我解决这个错误并解释 encode("utf-8")
和 unicode()
函数的正确用法吗?我经常和它打架。
这个 execute()
语句引发了错误:
cur.execute("update docs set path = :fullFilePath where path = :path", locals())
我忘了更改 fullFilePath
变量的编码,它遇到了同样的问题,但我现在很困惑。我应该只使用 unicode()
或 encode("utf-8")
还是两者都使用?
我无法使用
fullFilePath = unicode(fullFilePath.encode("utf-8"))
因为它引发了这个错误:
UnicodeDecodeError:“ascii”编解码器无法解码位置 32 中的字节 0xc5:序数不在范围内(128)
Python 版本为 2.7.2
原文由 xralf 发布,翻译遵循 CC BY-SA 4.0 许可协议
您正在错误地使用
encode("utf-8")
。 Python 字节字符串(str
类型)有编码,Unicode 没有。您可以使用uni.encode(encoding)
将 Unicode 字符串转换为 Python 字节字符串,并且可以使用s.decode(encoding)
(或等效地,unicode(s, encoding)
)将字节字符串转换为 Unicode 字符串)。如果
fullFilePath
和path
当前是str
类型,您应该弄清楚它们是如何编码的。例如,如果当前编码是 utf-8,您将使用:如果这不能解决它,实际问题可能是您没有在
execute()
调用中使用 Unicode 字符串,请尝试将其更改为以下内容: