相关疑难解决方法(0)

为什么我们不应该在py脚本中使用sys.setdefaultencoding("utf-8")?

我见过很少的py脚本在脚本的顶部使用它.在什么情况下应该使用它?

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud)

python encoding utf-8 python-2.x sys

158
推荐指数
3
解决办法
18万
查看次数

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

我有一个路径变量编码问题并将其插入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 …

python sqlite string unicode encoding

79
推荐指数
2
解决办法
25万
查看次数

Django + sqlite + Unicode

我在通过管理站点向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

python django unicode

3
推荐指数
1
解决办法
1981
查看次数

标签 统计

python ×3

encoding ×2

unicode ×2

django ×1

python-2.x ×1

sqlite ×1

string ×1

sys ×1

utf-8 ×1