cuylar cuylar - 1 month ago 15
Python Question

Please explain this unexpected \b (backspace) behavior

Expected:

>>> print "I print\b\b Backspace\b\b!"
I pri Backspa!
>>> print "I print\b\b Backspace\b\b\b!"
I pri Backsp!


Observed:

>>> print "I print\b\b Backspace\b\b!"
I pri Backspa!e
>>> print "I print\b\b Backspace\b\b\b!"
I pri Backsp!ce


Why does is 'e' and 'ce' not erased and '!' inserted?

Answer

The \b also termed as back space moves back the cursor by 1.

The backspace doesn't delete anything, it moves the cursor to the left and it gets covered up by what you write afterwards.

Let's understand this with your example:

"I print\b\b Backspace\b\b!"    # original string passed to "print"
#     ^^ * *        ^^ * *
#     12 1 2        34 3 4
  • After executing *1 and *2, cursor comes at ^1. Hence, ^1 is replaced by space ' ' and ^2 replaced by B (characters following \b)

  • After executing *3, and *4, cursor comes at ^3 and is replaced by !. Since there was nothing after !, ^4 remains as it is, else would have be replaced by the next character.

Hence the resultant content that is printed on the screen is as:

I pri Backspa!e