Mike
Mike

Reputation: 33

Print string in a form of Unicode codes

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

Input: "если" (in Russian).

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

Upvotes: 3

Views: 386

Answers (4)

Torsten Marek
Torsten Marek

Reputation: 86492

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

Upvotes: 1

lightman
lightman

Reputation: 31

If you need a specific encoding, you can use :

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

Upvotes: 0

Michał Niklas
Michał Niklas

Reputation: 54292

Code:

txt = u"если"
print repr(txt)

Output:

u'\u0435\u0441\u043b\u0438'

Upvotes: 3

DisplacedAussie
DisplacedAussie

Reputation: 4694

This should work:

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

Upvotes: 9

Related Questions