Python 中 unicode() 和 encode() 函数的使用

新手上路,请多包涵

我在编码 路径 变量并将其插入 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 许可协议

阅读 1k
2 个回答

您正在错误地使用 encode("utf-8") 。 Python 字节字符串( str 类型)有编码,Unicode 没有。您可以使用 uni.encode(encoding) 将 Unicode 字符串转换为 Python 字节字符串,并且可以使用 s.decode(encoding) (或等效地, unicode(s, encoding) )将字节字符串转换为 Unicode 字符串)。

如果 fullFilePathpath 当前是 str 类型,您应该弄清楚它们是如何编码的。例如,如果当前编码是 utf-8,您将使用:

 path = path.decode('utf-8')
fullFilePath = fullFilePath.decode('utf-8')

如果这不能解决它,实际问题可能是您没有在 execute() 调用中使用 Unicode 字符串,请尝试将其更改为以下内容:

 cur.execute(u"update docs set path = :fullFilePath where path = :path", locals())

原文由 Andrew Clark 发布,翻译遵循 CC BY-SA 3.0 许可协议

str 是以字节为单位的文本表示, unicode 是以字符为单位的文本表示。

您将文本从字节解码为 unicode,然后使用某种编码将 unicode 编码为字节。

那是:

 >>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020 :答案是在主要使用 Python 2 时编写的。 In Python 3, str was renamed to bytes , and unicode was renamed to str .

 >>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

原文由 newtover 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题