【问题标题】:UnicodeDecodeError using Django smart_str with European lettersUnicodeDecodeError 使用带有欧洲字母的 Django smart_str
【发布时间】:2019-06-30 15:11:19
【问题描述】:

我收到了错误

UnicodeDecodeError:“ascii”编解码器无法解码位置 138 中的字节 0xc3:序数不在范围内 (128)

当我尝试做的时候

from django.utils.encoding import smart_str

u'{}'.format(smart_str('ø'))

但是documentation 说这个函数的默认编码是utf-8,我认为应该包括'ø'。我在 Python 2.7 上使用 Django 1.11。我在这里错过了什么?

【问题讨论】:

  • 你的 python 和 django 版本是多少?我试过你的代码,但它没有引发错误。我的python版本是3.7,django版本是2.1.5
  • 将这些细节添加到我的问题中。

标签: python django python-2.7 utf-8 character-encoding


【解决方案1】:

所以阅读this post 我发现 Python 2.7(但不是 Python 3.x)在 utf-8 和 unicode 之间转换存在问题。谁会想它?所以我需要在格式化之前解码我的字符串:

u'{}'.format(smart_str('ø').decode('utf-8'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2011-03-06
    • 2012-09-22
    • 2010-10-28
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多