【问题标题】:Error in encoding string编码字符串错误
【发布时间】:2017-03-08 13:47:56
【问题描述】:

这可能是一个非常简单的问题,但我无法解决它。

在我的 python 控制台中我这样做:

request.request.data.get('comment')

我收到{u'price': u'21', u'unit': u'30\xd730', u'name': u'test', u'comments': u'check'}

comment的值原来是:

            "comments" : "check",
            "name" : "test",
            "price" : "21",
            "unit" : "30×30"(multiplication sign x)

我怎样才能解决这个问题,使我得到request.request.data.get('comment'){u'price': u'21', u'unit': u'30x30', u'name': u'test', u'comments': u'check'}

我尝试使用:

request.request.data.get('comment').get('unit').encode('utf-8')

但它返回'30\xc3\x9730'

我想将/xd 转换为ascii。

【问题讨论】:

  • 使用str函数获取字符串str(request.request.data.get('comment'))
  • {u'price': u'21', u'unit': u'30\\xd730', u'name': u'test', u'cmets': u'check '} 得到了这个。

标签: python string python-2.7 encoding


【解决方案1】:

u'something' 只是 Python 在列表、字典或元组中显示 unicode 字符串的方式。

如果您将值打印到字符串本身 (print request.request.data.get('comment').get('unit')),您将获得实际字符。

除非你的终端不支持它(或者如果 python 这么认为)。 您可以尝试使用编解码器模块强制特定编码:

sys.stdout=codecs.getwriter('utf-8')(sys.stdout)

【讨论】:

    【解决方案2】:

    这似乎是方法中的一个特性(错误?)

    dict.__repr__() 
    

    和/或

    dict.__str__() 
    

    Python 2.7.x。真的一切都好。你可以检查一下

    print a[u'unit']
    

    打印出来的

    30x30
    

    附: Python 3.5.2 没有问题...

    在 unicode Pycharm 控制台中查看下面的 Python 2.7 交互式会话:

    Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
    >>> a=u'\xd7'
    >>> a
    u'\xd7'
    >>> print a
    ×
    

    【讨论】:

    • comment['unit'] 不适用于我的代码。它给了comment['unit'] = u'30\xd730'
    • 打印函数可以将其打印为普通字符串,但我使用的是 str(comment.get('unit')) 之类的东西
    • 在 Python 2.7 中 str 只是一个字节序列......没有编码等......这就是你看到转义符号的原因。我想你会在 str(comment.get('unit')) 中得到 UnicodeEncodeError
    • 去掉str(...),因为它的参数是一个带有乘号\xd7的Unicode对象,不能自动转换成ASCII,然后用print把结果显示给你的用户程序。或者尽可能使用 Python 3.x。
    猜你喜欢
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多