【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)UnicodeEncodeError:'ascii' 编解码器无法在位置 4 编码字符 u'\xa0':序数不在范围内(128)
【发布时间】:2018-07-10 01:18:07
【问题描述】:

我在使用 Unicode 时遇到了一些问题。我是编程初学者,所以在这里我无法理解与此问题相关的其他答案。

追溯

Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/django_project/learn/views.py" in index
  19.         if str(get_one_phrasalverb) not in cannot_be_random:

Exception Type: UnicodeEncodeError at /learn/keep-from/
Exception Value: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)

有问题的代码部分

cannot_be_random = request.session.get('cannot_be_random')

if str(get_one_phrasalverb) not in cannot_be_random:
     cannot_be_random.append(str(get_one_phrasalverb))
     request.session['cannot_be_random'] = cannot_be_random

如果缺少部分代码或部分回溯,请告诉我。

有人可以帮帮我吗?

【问题讨论】:

    标签: python django unicode python-2.x


    【解决方案1】:

    问题在str(get_one_phrasalverb) 内部。错误表示get_one_phrasalverb 无法使用ascii 编码转换为str

    所以你需要先知道get_one_phrasalverb的编码,如果编码是utf8,你可以用get_one_phrasalverb.encode('utf8')代替str(get_one_phrasalverb)

    【讨论】:

    • 感谢您的回答。现在我得到:对象没有属性“编码”。你知道它可能是什么吗?
    • get_one_phrasalverb的类型是什么,可以打印type(get_one_phrasalverb)
    • 由于它的类型不是unicode,所以需要在PhrasalVerb__str____repr__方法中进行编码
    • 如果self.name是一个字符串,你可以这样做
    猜你喜欢
    • 2012-04-14
    • 2020-04-04
    • 2016-08-26
    • 2017-03-29
    • 2011-07-05
    • 2016-09-05
    • 2013-02-11
    • 2012-05-06
    • 2019-12-15
    相关资源
    最近更新 更多