1

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

print("12\b345")
print("12345\b\b")
print("12345\b\ba")

output:

1345
12345
123a5

I was expecting:

1345
123
123a
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • If any of the answers below solved your issue, then consider marking the one that best helped you as correct. This will help guide others with the same issue in the future. – Michael M. Mar 03 '23 at 06:07

2 Answers2

2

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("12\b \b345")
print("12345\b \b\b \b")
print("12345\b \b\b \ba")
Michael M.
  • 10,486
  • 9
  • 18
  • 34
1

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 "12\b345" 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 "12345\b\b" 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 "12345\b\ba" 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".
Axzyte g
  • 38
  • 5