Why does Python backspace behave strange?

Question:

Python escape character b (backspace) behaves in a strange way.
Just look at the code below:

print("12b345")
print("12345bb")
print("12345bba")

output:

1345
12345
123a5

I was expecting:

1345
123
123a
Asked By: user3809022

||

Answers:

The backspace character doesn’t actually work like the backspace on your computer. It only moves the cursor back one position. So, unless you overwrite the text, it won’t change.

The behavior you’re looking for can be easily accomplished with b b (move back one space, type an empty space, then move back onto that space). Like this:

print("12b b345")
print("12345b bb b")
print("12345b bb ba")
Answered By: Michael M.

The backspace escape character (b) in Python is used to move the cursor back one space, without deleting the character at that position.
When combined with other characters in a string, the backspace escape character can be used to create some interesting effects.

  • In the first line of the code, the string "12b345" is printed.
    The backspace escape character (b) is used to move the cursor back one space after the "2" in "12", and then the "3" is printed, effectively overwriting the "2". Therefore, the output is "1345".
  • In the second line of the code, the string "12345bb" is printed. The backspace escape character (b) is used to move the cursor back two spaces after the "5" in "12345", effectively deleting the "5" and leaving the string as "1234". Therefore, the output is "12345".
  • In the third line of the code, the string "12345bba" is printed. The backspace escape character (b) is used to move the cursor back one space after the "5" in "12345", effectively deleting the "5" and leaving the string as "1234". Then, the letter "a" is printed, effectively inserting it after the "3". Therefore, the output is "123a5".
Answered By: Axzyte g
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.