Cuylar Conly
Cuylar Conly

Reputation: 685

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?

Upvotes: 1

Views: 173

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48057

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

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49320

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!

Upvotes: 1

Prune
Prune

Reputation: 77827

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!

Upvotes: 3

Related Questions