Print string as Unicode codes

How can I print a string as a sequence of Unicode codes in Python?

Entrance: ""(in Russian).

Output: "\u0435\u0441\u043b\u0438"

+3
source share
4 answers

This should work:

>>> s = u''
>>> print repr(s)
u'\u0435\u0441\u043b\u0438'
+9
source

the code:

txt = u""
print repr(txt)

Output:

u'\u0435\u0441\u043b\u0438'
+3
source
a = u"\u0435\u0441\u043b\u0438"
print "".join("\u{0:04x}".format(ord(c)) for c in a)
+1
source

If you need a specific encoding, you can use:

txt = u''
print txt.encode('utf8')
print txt.encode('utf16')
0
source

Source: https://habr.com/ru/post/1731525/


All Articles