请问如何用更简单的方式获取中文字符的uncode编码

4 views
Skip to first unread message

sypxue

unread,
Dec 19, 2010, 10:01:00 PM12/19/10
to pyth...@googlegroups.com
def getuncodestr(s):
a = StringIO.StringIO()
b = sys.stdout
sys.stdout = a
print [s]
sys.stdout = b
a.seek(0)
c = a.readline()
a.close()
return c[3:-3]

if __name__=="__main__":
print getuncodestr(u'中国人')

结果:
\u4e2d\u56fd\u4eba
请问有更简单的方式吗?

Leo Jay

unread,
Dec 19, 2010, 10:06:40 PM12/19/10
to pyth...@googlegroups.com
2010/12/20 sypxue <syp...@gmail.com>:

ord这个函数满足你的要求吗?

>>> s = u'中国人'
>>> [hex(ord(c)) for c in s]
['0x4e2d', '0x56fd', '0x4eba']
>>>

--
Best Regards,
Leo Jay

sypxue

unread,
Dec 19, 2010, 10:15:29 PM12/19/10
to pyth...@googlegroups.com
恩,非常感谢,就是这个了

> --
> 来自: python-cn`CPyUG`华蟒用户组(中文Python技术邮件列表)
> 发言: pyth...@googlegroups.com
> 退订: python-cn+...@googlegroups.com (向此发空信即退!)
> 详情: http://code.google.com/p/cpyug/wiki/PythonCn
> 严正: 理解列表! 智慧提问! http://wiki.woodpecker.org.cn/moin/AskForHelp
>

duyue

unread,
Dec 19, 2010, 10:16:47 PM12/19/10
to pyth...@googlegroups.com
>>> s = u'中国人'
>>> repr(s)[2:-2]
'\\u4e2d\\u56fd\\u4eb'

sypxue

unread,
Dec 19, 2010, 10:24:47 PM12/19/10
to pyth...@googlegroups.com
受教,看来对很多函数很不熟悉
要努力啦!!

Phus Lu

unread,
Dec 19, 2010, 11:19:39 PM12/19/10
to pyth...@googlegroups.com
u'中国人'.encode('unicode-escape')
--
Best Regards
Phus Lu

Reply all
Reply to author
Forward
0 new messages