0

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

Rizhiy
  • 775
  • 1
  • 9
  • 31
  • 2
    Do raw strings solve your problem: `r"\b"`? – mcsoini Jun 26 '21 at 07:36
  • A very similar question was asked not so long ago. Sadly, I cannot find it. If I am not mistaken, there is no consistent way to display escaped characters literally. `repr` works for some characters but not for all. – DYZ Jun 26 '21 at 07:49
  • `str()` and `repr()` have default handling. If you don't like the default. Write your own function and replace it yourself. Something like `'a\bc'.replace('\b',r'\b')` – Mark Tolonen Jun 26 '21 at 19:51

2 Answers2

1

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
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
1

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'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251