10

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?

Community
  • 1
  • 1
Sumod
  • 3,806
  • 9
  • 50
  • 69
  • 7
    The backspace doesn't delete anything, it moves the cursor to the left and it gets overwritten by what you write afterwards. – alexis Mar 12 '12 at 13:03
  • It certainly is, but I didn't like the answer (the author seems to have never heard of hard copy terminals), so I've added my own here. – alexis Mar 12 '12 at 13:14

2 Answers2

14

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.

alexis
  • 48,685
  • 16
  • 101
  • 161
12

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"

Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45
dbr
  • 165,801
  • 69
  • 278
  • 343