Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - string of binary escape sequences as literal

Tags:

python

string

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?

like image 485
Amit Avatar asked Nov 06 '12 23:11

Amit


People also ask

How do you escape a string literal in Python?

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.

Is escape sequence a literal?

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.

Can escape sequences only be used in strings?

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.

How do you handle escape sequence in Python?

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.


1 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 ])
like image 159
Michael Lorton Avatar answered Oct 15 '22 21:10

Michael Lorton