python 转unicode_在python中转换unicode字符串

{u'Status': u'OK', u'City': u'Ciri\xe8', u'TimezoneName': '', u'ZipPostalCode': '', u'CountryCode': u'IT', u'Dstoffset': u'0', u'Ip': u'x.x.x.x', u'Longitude': u'7.6', u'CountryName': u'Italy', u'RegionCode': u'12', u'Latitude': u'45.2333', u'Isdst': '', u'Gmtoffset': u'0', u'RegionName': u'Piemonte'}

This is the output of my object. I would like to access City but It's encoded. How can I read all parameters and decode it

>>> data['City']

u'Ciri\xe8'

>>>data['City'].decode('utf-8')

Traceback (most recent call last):

File "", line 1, in

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode

return codecs.utf_8_decode(input, errors, True)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 4: ordinal not in range(128)

I want plaintext not unicode string. Thank you!

解决方案

Then just print it:

>>> data = {u'City':u'Ciri\xe8'}

>>> data['City']

u'Ciri\xe8'

>>> print data['City']

Ciriè

If you don't print it, Python prints a safe representation of the string, indicating it is Unicode text u'', and that it contains a non-ASCII character \xe8. print attempts to display the non-ASCII character by encoding the Unicode string in the terminal encoding. It may fail if the string contains characters that aren't supported by the terminal encoding:

>>> print u'\xe8'

è

>>> print u'\x81'

Traceback (most recent call last):

File "", line 1, in

File "d:\dev\Python27\lib\encodings\cp437.py", line 12, in encode

return codecs.charmap_encode(input,errors,encoding_map)

UnicodeEncodeError: 'charmap' codec can't encode character u'\x81' in position 0: character maps to

In the above example, code page 437 supports Unicode character U+00E8, but not U+0081.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值