I have a problem with deleting a character in python3 chr(8)

Viewed 65

For example

print("a" + chr(8)) result is a, but when i run print("a" + chr(8) + "b") result is b, even if I do

print("a" + chr(8) + "") result is a why is that happening? Why my first line of code just don't simply delete this character?

3 Answers

Python itself doesn’t treat backspace specially. What you are probably seeing is the terminal interpreting the backspace specially by moving the cursor left (without erasing anything).

In the terminal, backspace moves the cursor back, and printing another character overwrites it. Therefore you don't see a when you supply b.

>>> s = "a" + chr(8) + "b"
>>> print(s)
b
>>> s
'a\x08b'
>>> s = ("a" + chr(8))
>>> s
'a\x08'

it doesn't delete it, your string has escape characters, you can check it yourself:

In [115]: mystr = "a" + chr(8) + "b"                                                                                                                                                                        

In [116]: mystr                                                                                                                                                                                             
Out[116]: 'a\x08b'

In [117]: print(mystr)                                                                                                                                                                                      
b

In the ascii table character 8 is backspace. Backspaces are handled by your operating system. The question to be asked is how does your operating system handle a backspace, because all python does is add \x08 to the string.

Related