ZengJuchen
ZengJuchen

Reputation: 4811

Why `print '1\x08'` results 1 meanwhile `print '1\x082'` results 2?

Today, I'm learning the built-in function chr. And through ascii-table search, I found \x08 means backspace. So I played a bit with it. But the result confused me:

In [52]: print '1\x08'
1

In [53]: print '1\x082'
2

It seems that only follow by another character, \x08 will behave like a backspace, why does this happened? How \x08 behaves in a string?

Upvotes: 1

Views: 468

Answers (3)

gatieme
gatieme

Reputation: 105

1---- backspace simply move the cursor to the left one space, and if you use the work or other editor it will also delete the left one character. and what you must know is that backspace is also a character the same as 1 or a.

2---- the terminal as our default output device, you can also put him as a file.

So if you use

  print '1\x08'

it means that you write a 1 and a backspace in the file stdout.

if you read the file, the system reads 1 + breakspace, you will get an 1.

and if you use

  print '1\x082'

it means that you write a 1, a backspace and a 2 in the file stdout.

if you read the file, the system get 1 + breakspace + 2, when you print them, you will only get an 2, because it covers the first 1 when you use backspace.

for detail you can see the next test code

  if __name__ == "__main__":
      print "1\x08"
      print "1\x082"

      f = open("1.txt", "w")
      f.write("1\x08\x082")
      f.close();

      f = open("1.txt", "r")
      str = f.readlines( )
      print len(str), str
      for s in str:
      print "s=|" + s + "|"

enter image description here

you can see the string s=|1\x08\x082| display s=2|. becasue the |1 not display when backspace two times.

Upvotes: 1

falstaff
falstaff

Reputation: 3693

Backspace only moves the cursor by one character, it does not actually delete it. This for example results in 193:

print('123\x08\x089')

You can use space to actually "delete" the character...

Upvotes: 1

Tom Karzes
Tom Karzes

Reputation: 24092

It's behaving like a backspace in both cases, which is to say it moves your cursor back one space. It does not, however, delete what's there unless you write something else. So in the first case, the 1 remains, but in the second it is overwritten with a 2.

Upvotes: 3

Related Questions