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?
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.
An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.
Use escape sequences only in character constants or in string literals. An error message is issued if an escape sequence is not recognized. In string and character sequences, when you want the backslash to represent itself (rather than the beginning of an escape sequence), you must use a \\ backslash escape sequence.
Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.
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 ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With