我见过很少的py脚本在脚本的顶部使用它.在什么情况下应该使用它?
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud) 我有一个路径变量编码问题并将其插入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 …
我在通过管理站点向sqlite数据库添加新记录时遇到了Unicode字符串问题.
class Translation(BaseModel):
.....
translation = models.CharField(max_length=100)
Run Code Online (Sandbox Code Playgroud)
当我尝试插入像'été'这样的单词时会发生错误:
**UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)**
Run Code Online (Sandbox Code Playgroud)
更新:添加了回溯:http://pastebin.com/yLYFNDGB