Please explain this unexpected \b (backspace) behavior

我的未来我决定 提交于 2020-03-22 09:47:11

问题


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?


回答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



回答2:


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!



回答3:


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!


来源:https://stackoverflow.com/questions/40251434/please-explain-this-unexpected-b-backspace-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!