I need to print out a string of binary escape sequences, e.g. \x05\x03\x87, exactly as they appear. When I try to print them, Python returns a string of weird non-ASCII characters. How can I print them as a string literal?
- 981
- 2
- 9
- 16
-
Please show some code. You seem to confuse the actual contents of a string with its representation in Python code, and we can only tell you what's the problem is if you show us the code. – Sven Marnach Nov 06 '12 at 23:34
3 Answers
repr
>>> a='\x05\x03\x87'
>>> print a
?
>>> print repr(a)
'\x05\x03\x87'
EDIT
Sven makes the point that the OP might want every character dumped in hex, even the printable ones, in which case, the best solution I can think of is:
>>> print ''.join(map(lambda c:'\\x%02x'%c, map(ord, a)))
\x05\x03\x87
ADDITIONAL EDIT
Four years later, it occurs to me that this might be both faster and more readable:
>>> print ''.join(map(lambda c:'\\x%02x'% ord(c), a))
or even
>>> print ''.join([ '\\x%02x'% ord(c) for c in a ])
- 43,060
- 26
- 103
- 144
-
-
At least from the wording of the question, he would want to print `'\x20'` exactly as it appears. I guess the problem is some confusion regarding string escaping, and I don't think the current answers resolve this confusion in any way. This answer has the additional problem that the representation of a string is implementation-defined, so you can't rely on this behaviour. – Sven Marnach Nov 06 '12 at 23:40
Use the string-escape encoding:
>>> print '\x05\x03\x87'.encode('string-escape')
\x05\x03\x87
From docs:
Produce a string that is suitable as string literal in Python source code
This will essentially give you the same thing as repr(), without those pesky quotes.
Note that like Malvolio's answer, this assumes that you only want the escaped version for non-printable characters, if this is not what you want please clarify.
- 202,379
- 35
- 273
- 306
You can derive your own subclass of str that behaves & prints the way you desire, yet can be used almost anywhere a regular string could be and has all the same built-in methods.
As you can see, the example prints the hex values of all the characters it contains, whether they're printable normally or not -- something which could be done differently if you wanted, of course.
class HexStr(str):
def __repr__(self):
return "'" + ''.join('\\x{:02x}'.format(ord(ch)) for ch in self) + "'"
__str__ = __repr__
a = HexStr('abc\x05\x03\x87')
print a
print str(a)
print repr(a)
Output:
'\x61\x62\x63\x05\x03\x87'
'\x61\x62\x63\x05\x03\x87'
'\x61\x62\x63\x05\x03\x87'
- 119,623
- 25
- 170
- 301