joseph rance
joseph rance

Reputation: 36

Python \b character acting strangely

I noticed that the \b (backspace) character was acting a little strangely. I usually run code in Google Colab, where the following code runs like:

Colab output

But when I run it on my own computer, it acts completely differently:

Other output

Does anyone know why that is happening, and is it possible to get the behaviour of the first image locally?

Upvotes: 0

Views: 513

Answers (1)

André C. Andersen
André C. Andersen

Reputation: 9405

This isn't really a python thing. It depends on whatever rendering comes after python hands it over for printing. Python simply gives the stream a sequence of characters. And it is up to the terminal or Google Colab to render it appropriately.

Then \b character instructs whatever is printing to move the cursor back one character, then you continue writing. It is not "backspace", it is "left arrow" if anything.

Your first print types a then moves the cursor to the left of a then types c, thus overwriting a with c. This prints the expected c.

The next print types d then moves the cursor to the left, then stops. This is the interesting print. In a terminal the print ends here, thus this line prints d. And the next print starts from scratch.

That means in a terminal the last line says to move the cursor left, there is no left there, so it is a NOP operation, then enter e. Which just prints e.

However, Google Colab seems to either keep the cursor alive between prints (I doubt it), or it sends a new line character using the same cursor which overwrites the d.

Without knowing exactly how it renders text it is hard to say.

More info can be found here: Python strings: backspace at the end of string behaves differently

Edit: Looking even more closely at it, it seems that it might just be a known issue with notebooks: https://github.com/jupyter/notebook/issues/5381#issuecomment-614982643

Seems like it is conflating \b as "backspace" instead of "left arrow" as I talked about in the start.

Upvotes: 4

Related Questions