Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backspace behavior in Python statement, what is correct behavior of printing a '\b' in code? [duplicate]

Tags:

python

Possible Duplicate:
backspace character weirdness

I have noticed that 1. If I print only backspaces, i.e. a sequence of \b in Python, then it is completely blank. 2. If I print characters followed by backspaces i.e. 'sssss\b\b\b\b\b', then it will print the multiple 's' characters But if I print something like 'ssss\b\b\b\baaaa', then the backspace, \b, will actually act like I am typing a backspace and delete the 's' characters.

I am using Python 2.6 on Windows XP. Is this expected behavior. If I try to get length of backspace character, it is printed as 1.

Here is my test code -

>>> print 'ssss\b\b\b\b\baaaaa'
aaaaa
>>> print 'ssssssss\b\b\b\b\baaaaa'
sssaaaaa
>>> print 'ssssssss\b\b\b\b\b'
ssssssss
>>> print 'ssssssss\b\b\b\b\baaaaa'
sssaaaaa
>>> print '\b\b\b\b\b'

>>>

My question is- What is the expected behavior when I print '\b' in Python and why the deletion does work in only a particular case?

like image 507
Sumod Avatar asked Mar 12 '12 13:03

Sumod


2 Answers

As Alexis said in the comment, it moves the cursor back (to the left by one character). Then when you print, it overwrites the character (applying only to the current line of text)

>>> print 'abc\b'
abc
>>> print 'abc\b\b\b'
abc
>>> print 'abc\b1'
ab1
>>> print 'abc\b\b\b123'
123

Nothing Python specific, as evidenced by "backspace character weirdness"

like image 146
dbr Avatar answered Oct 15 '22 00:10

dbr


Expanded answer: The backspace doesn't delete anything, it moves the cursor to the left and it gets covered up by what you write afterwards. If you were writing to a device that can display overstriking (such as an old-fashioned "hard copy" terminal, which works like a typewriter), you'd actually see the new character on top of the old one. That's the real reason backspace has these semantics.

On the unix command line, the shell can be set to interpret backspace as meaning "erase"-- unless it's set to only treat delete this way. But that's up to the program reading your input.

like image 26
alexis Avatar answered Oct 15 '22 00:10

alexis