0
for i in range(0, 100):
    print(i, end="\r")

Works as expected, where it writes the next number to sys.stdout in the same position as the last number

0
1
...
100

But if the numbers decrease, such as

for i in range(101, 0, -1):
    print(i, end="\r")

It spits out something like:

100 # this is supposed to be 100
990 # 99
980 # 98
...
100 # 1

Any ideas?

I did attempt to use the \b trick, but that yielded the same result as using \r.

I also did the same with flush=True, but no difference

I was expecting the line to be completely void of any previous number that came before it, such as

100
99
98
...
1
Bingus
  • 37
  • 3
  • Is there anyway to force it to discard the previous letters before printing the smaller one? – Bingus Jul 25 '23 at 15:40
  • Do not use `\r`. Use `\n` instead or check how your exact terminal works. Also considering that Python uses universal new line (when reading in text mode), so it can add confusion: `\r` is interpreted as `\n` (but when followed by `\n`). – Giacomo Catenazzi Jul 26 '23 at 06:52

1 Answers1

2

\r returns the writing cursor to the beginning of the line and \b returns one character back. They don't erase anything.

If you want real erasing, you should write spaces. E.g. "human" backspace (what would you expect while writing on a keyboard) is \b \b -> move cursor one back, write space to overwrite that character, move cursor back again to be before the space.

So let's say you know that your thing will take at most 3 characters. We can tell python string formatting "this thing will take 3 characters".

By default, numbers are right-aligned with it:

print(f"{i:3}", end="\r")

But we can use < to force left-alignment:

print(f"{i:<3}", end="\r")

Left-aligned numbers padded to always take 3 spaces is what matches what you want

h4z3
  • 5,265
  • 1
  • 15
  • 29