bebop bebop - 4 years ago 252
Python Question

How can I get python ''.encode('unicode_escape') to return escape codes for ascii?

I am trying to use the

method of python strings to return the unicode escape codes for characters, like this:

>>> print( 'ф'.encode('unicode_escape').decode('utf8') )

This works fine with non-ascii characters, but for ascii characters, it just returns the ascii characters themselves:

>>> print( 'f'.encode('unicode_escape').decode('utf8') )

The desired output would be
. This script is for pedagogical purposes.

How can I get the unicode hex codes for ALL characters?

wim wim
Answer Source

Your request is kind of weird. In Python, usually we would just use ord for that instead. There is not need for encoding/decoding here.

>>> '"\\U{:08x}"'.format(ord('f'))  # ...or \u{:04x} if you prefer
>>> eval(_)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download