Search code examples
pythonpython-2.7unicode

Force output of ascii string as bytes


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

>>> 'юникод'
'\xd1\x8e\xd0\xbd\xd0\xb8\xd0\xba\xd0\xbe\xd0\xb4'

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?


Solution

  • Try the following:

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

    Gives:

    \x75\x6e\x69\x63\x6f\x64\x65