Force output of ascii string as bytes

Question:

If I am trying to explore non-ascii string in interactive python session:

>>> 'юникод'
'xd1x8exd0xbdxd0xb8xd0xbaxd0xbexd0xb4'

it gets me string as bytes (since str in python 2 is actually bytes)

I want to get same representation for ascii string, but python implicitly converts it to string representation

>>> 'unicode'
'unicode'

How could I disable such behavior?
Or I should build such functionality manually?

Asked By: xiº

||

Answers:

Try the following:

s = 'unicode'
print ''.join(['\x%02x' % (ord(c)) for c in s])

Gives:

x75x6ex69x63x6fx64x65
Answered By: cdarke

If you just want to quickly inspect the hex values:

>>> s = 'unicode'
>>> s.encode('hex_codec')
'756e69636f6465'
Answered By: ekhumoro
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.