Python 以Unicode代码的形式打印字符串

Python 以Unicode代码的形式打印字符串,python,string,unicode,Python,String,Unicode,如何在Python中将字符串打印为unicode代码序列 输入:“Сббб”(俄语) 输出:“\u0435\u0441\u043b\u0438”这应该可以: >>> s = u'если' >>> print repr(s) u'\u0435\u0441\u043b\u0438' 代码: 输出: u'\u0435\u0441\u043b\u0438' 如果需要特定编码,可以使用: txt = u'если' print txt.encode('utf8')

如何在Python中将字符串打印为unicode代码序列

输入:
“Сббб”
(俄语)

输出:
“\u0435\u0441\u043b\u0438”

这应该可以:

>>> s = u'если'
>>> print repr(s)
u'\u0435\u0441\u043b\u0438'
代码:

输出:

u'\u0435\u0441\u043b\u0438'

如果需要特定编码,可以使用:

txt = u'если'
print txt.encode('utf8')
print txt.encode('utf16')

当然可以,但它也为ascii字符提供了unicode,这可能是需要的。但您应该在该列表周围有一个“”。join()@莱纳特:是的,谢谢你。从repr的返回值中提取字符串有点繁琐(在Python3中会发生变化,因为u前缀已经消失)。
a = u"\u0435\u0441\u043b\u0438"
print "".join("\u{0:04x}".format(ord(c)) for c in a)
txt = u'если'
print txt.encode('utf8')
print txt.encode('utf16')