1

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?

Cuylar Conly
  • 635
  • 1
  • 6
  • 11

3 Answers3

3

You didn't erase them; you merely backspaced. Going forward will overwrite the previous characters, but backspace doesn't erase as it backs up. You would want

print "I print\b\b Backspace\b\b  !"

... to see ...

I pri Backspa  !

If you want the "full effect", you have to backspace and overwrite wtih spaces as you back up ... then you can move forward. Something like

print "Backspace" + 2*"\b \b" + "!"

You can use the multiplier as many times as you wish; it's a small motif. The above line displays

Backspa!
Prune
  • 76,765
  • 14
  • 60
  • 81
1

The \b character moves the carriage back by one space, similar to how \r moves the carriage all the way back to the beginning of the line. If you don't overwrite the characters you backed up over, they will still be there.

>>> print "I print\b\b Backspace\b\b!"
I pri Backspa!e
>>> print "I print\b\b Backspace\b\b! "
I pri Backspa!
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

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
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126