免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3179 | 回复: 2

unicode 强制类型转换 [复制链接]

论坛徽章:
0
发表于 2014-05-23 14:01 |显示全部楼层
本帖最后由 fengidri 于 2014-05-23 14:06 编辑
  1. Python 2.7.6 (default, Feb 26 2014, 12:07:17)
  2. [GCC 4.8.2 20140206 (prerelease)] on linux2
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >>> a="帖子"
  5. >>> a
  6. '\xe5\xb8\x96\xe5\xad\x90'
  7. >>> b=u'\xe5\xb8\x96\xe5\xad\x90'
  8. >>> b
  9. u'\xe5\xb8\x96\xe5\xad\x90'
  10. >>> print b
  11. å¸å­
  12. >>> print b.encode('utf8')
  13. å¸å­
  14. >>>


复制代码
这里的对象b是一个unicode 但是保存的编码是ascii的。 我们如何把这个对象转移成正确的编码。


谢谢

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
发表于 2014-05-23 14:42 |显示全部楼层
这用法,自讨苦吃啊

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
发表于 2014-05-23 14:58 |显示全部楼层
本帖最后由 timespace 于 2014-05-23 14:58 编辑

还好有bytearray,不是太复杂,完整尝试过程:
  1. Python 2.7.5 (default, Mar  9 2014, 22:15:05)
  2. [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >>> a = "帖子"
  5. >>> a
  6. '\xe5\xb8\x96\xe5\xad\x90'
  7. >>> b = unicode(a)
  8. Traceback (most recent call last):
  9.   File "<stdin>", line 1, in <module>
  10. UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
  11. >>> b = u'\xe5\xb8\x96\xe5\xad\x90'
  12. >>> b
  13. u'\xe5\xb8\x96\xe5\xad\x90'
  14. >>> print b
  15. 帖å-
  16. >>> [ord(e) for e in b]
  17. [229, 184, 150, 229, 173, 144]
  18. >>> bytearray(ord(e) for e in b)
  19. bytearray(b'\xe5\xb8\x96\xe5\xad\x90')
  20. >>> bytearray(ord(e) for e in b).decode('utf-8')
  21. u'\u5e16\u5b50'
  22. >>> c = bytearray(ord(e) for e in b).decode('utf-8')
  23. >>> c
  24. u'\u5e16\u5b50'
  25. >>> print c
  26. 帖子
  27. >>> d = c.encode('utf-8')
  28. >>> d
  29. '\xe5\xb8\x96\xe5\xad\x90'
  30. >>>
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP