Python中unicode字符串强制转换的问题

2013-02-25 21:05:35 +08:00
 Yo_oY
在Python里面使用unicode型的字符是这样:
>>> a = u'你好'
>>> a
>>> u'\u4f60\u597d'
>>> print a
>>> 你好

那我现在有个字符串是str型的,而且内容已经是unicode编码,比如:
>>> b = '\u4f60\u597d'
>>> b
>>> '\\u4f60\\u597d'
>>> print b
>>> \u4f60\u597d

现在要将b转换成unicode的“你好”,也就是a那样,该怎么做?

谢谢大家!
8820 次点击
所在节点    问与答
7 条回复
Yo_oY
2013-02-25 21:29:54 +08:00
自己找到了,XD
Via: http://hi.baidu.com/kanif/item/398612af052770ad29ce9d99

def ustr2unicode(input):
end = len(input)
pos = 0
output = u""
while pos < end:
if pos <= end - 6 and input[pos] == '\\' and input[pos+1] == 'u':
output += unichr(int(input[pos+2:pos+6], 16))
pos = pos + 6
else:
output += unicode(input[pos])
pos += 1

return output
reorx
2013-02-25 21:39:28 +08:00
lianghai
2013-02-25 23:18:50 +08:00
给一楼跪……
reorx
2013-02-25 23:52:54 +08:00
@Yo_oY 忽然发现。。我们好像在一个 clan 里 :D
Yo_oY
2013-02-26 00:49:33 +08:00
@reorx 原来可以这么简单。是在一个Clan啊,你的名字印象蛮深的,还想问你是不是那个虾米播放器的作者来着。
swulling
2013-02-26 01:29:02 +08:00
lz一般是要解析js中的unicode吧。。。
Yo_oY
2013-02-26 07:20:07 +08:00
@swulling 完全正确。。。

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

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

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

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

© 2021 V2EX