python 字符编码问题:u'\xb2\xe2\xca\xd4',类型为unicode,实际编码为utf-8,如何读取?

2013-12-07 17:38:37 +08:00
 yingluck
13529 次点击
所在节点    Python
13 条回复
ushuz
2013-12-07 17:59:40 +08:00
转成str
str()
yingluck
2013-12-07 18:14:10 +08:00
@ushuz 转成了 但是a[3:-1]这样取出来还是读取不了啊
Hackathon
2013-12-07 18:26:42 +08:00
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = u'\xb2\xe2\xca\xd4'
>>> b = a.encode('raw_unicode_escape')
>>> print b
测试
>>> c = a.encode('latin1')
>>> print c
测试
>>>
yingluck
2013-12-07 18:29:47 +08:00
@Hackathon 行啊 哈哈哈哈 可以了! 多谢 我要把你这种方法好好学一下!
sandtears
2013-12-07 19:59:10 +08:00
@Hackathon 多谢,我也一直很想知道这个orz
lnehe
2013-12-07 20:07:45 +08:00
python的字符编码问题一直搞不懂。。。
F0ur
2013-12-07 20:15:01 +08:00
python的字符编码一直个要研究的问题- -
9hills
2013-12-07 20:18:23 +08:00
这个不是字符编码问题<_<
VYSE
2013-12-07 20:29:14 +08:00
标题里的就是'\xb2\xe2\xca\xd4'就是GB2312编码的,加u在encode转换其实蛮诡异的,不过latin1还能encode说明Python根据OS环境做了些取舍,放在英文默认编码系统里肯定转不出来。

附言里是utf-8的,
print '\xe5\xbe\xae\xe4\xbf\xae'.decode('utf-8')即可。

\x出现在u''里表示的就不是byte而是等效于\u00XX,
比如u'\xe5\xbe\xae\xe4\xbf\xae'其实等于u'\u00e5\u00be\u00ae\u00e4\u00bf\u00ae',这样表示的是unicode char table里的第XX位而不是字节,意义就全变了。

反正bytes出现在unicode str里实在诡异。
shenGun
2013-12-11 15:49:15 +08:00
http://docs.python.org/2/howto/unicode.html
Latin-1, also known as ISO-8859-1, is a similar encoding. Unicode code points 0-255 are identical to the Latin-1 values, so converting to this encoding simply requires converting code points to byte values; if a code point larger than 255 is encountered, the string can’t be encoded into Latin-1.

在Documentation中提示unicode的0-255编码和Latin-1的0-255是一样的。说以u'\xb2\xe2\xca\xd4'.decode('Latin-1')转好之后就是'\xb2\xe2\xca\xd4'其实好像还是GB2312的编码
borneo
2013-12-15 21:19:34 +08:00
hey man.

by the way, keep it compatible with Python 2+3. http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
yingluck
2014-08-22 18:25:08 +08:00
http://hgoldfish.com/blogs/article/56/
直到发现了这个资料
lzjun
2016-08-11 14:46:24 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/92197

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX