e.g how do I print \b
as '\b' rather than '\x08'?
My current attempt is: value = repr(value)[1:-1]
, but that just prints out the code.
It seemed to work fine for \t
and \n
, but doesn't work for backspace
e.g how do I print \b
as '\b' rather than '\x08'?
My current attempt is: value = repr(value)[1:-1]
, but that just prints out the code.
It seemed to work fine for \t
and \n
, but doesn't work for backspace
repr
doesn't know about all the backslash escapes; besides your \b
(BS="backspace") example, there are also \a
("alert", for the BEL character that should make your terminal beep), \f
(FF="form feed", which originally moved to a new piece of paper in the printer and clears some terminal screens), and \v
(for VT="vertical tab"), for which repr
similarly returns hex codes ('\x07'
, '\x0c'
, and '\x0b'
, respectively). Your best bet is probably to roll your own function that does the replacements you want, e.g.:
def compact_repr(s):
r = repr(s)
for x, b in { r'\x07': r'\a', r'\x08': r'\b',
r'\x0b': r'\v', r'\x0c': r'\f' }.items():
r = r.replace(x, b)
return r
You have to make your own function if you don't like the repr()
default. Here's a brute force way to handle escape codes that repr()
doesn't:
def better_repr(s):
return repr(s).replace(r'\x07',r'\a').replace(r'\x08',r'\b').replace(r'\x0b',r'\v').replace(r'\x0c',r'\f')
print(repr('\a\b\n\r\t\v\f'))
print(better_repr('\a\b\n\r\t\v\f'))
Output:
'\x07\x08\n\r\t\x0b\x0c'
'\a\b\n\r\t\v\f'