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

xra*_*alf 79 python sqlite string unicode encoding

我有一个路径变量编码问题并将其插入SQLite数据库.我尝试使用编码("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'>
Run Code Online (Sandbox Code Playgroud)

最后我获得了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())
Run Code Online (Sandbox Code Playgroud)

我忘了改变遇到同样问题的fullFilePath变量的编码,但我现在很困惑.我应该只使用unicode()编码("utf-8")还是两者都使用?

我不能用

fullFilePath = unicode(fullFilePath.encode("utf-8"))
Run Code Online (Sandbox Code Playgroud)

因为它引发了这个错误:

UnicodeDecodeError:'ascii'编解码器无法解码位置32中的字节0xc5:序数不在范围内(128)

Python版本是2.7.2

new*_*ver 118

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

您将文本从字节解码为unicode,并使用某种编码将unicode编码为字节.

那是:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc' 
Run Code Online (Sandbox Code Playgroud)

  • Python 3.8 &gt;&gt; `'str' 对象没有属性 'decode'` (3认同)

And*_*ark 83

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

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

path = path.decode('utf-8')
fullFilePath = fullFilePath.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

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

cur.execute(u"update docs set path = :fullFilePath where path = :path", locals())
Run Code Online (Sandbox Code Playgroud)