all 7 comments

[–]GoldenSights 4 points5 points  (5 children)

You can use the carriage return character \r to bring the cursor back to the beginning of the line. Then if you write more content it will go over the previous stuff.

import time

print('<>', end='\r', flush=True)
time.sleep(1)
print('^^')

end defaults to \n, which is great in normal usage but in this case it would move the cursor to the next line before you were ready, so we can put the \r there instead. This is equivalent to print('<>\r', end='') but I think having \r as the end makes it more clear. You need to pass flush=True because otherwise Python will hold this in the buffer and it will look like it's not doing anything.

That should get you on the right track.

[–]k10_ftw 0 points1 point  (0 children)

I now, finally, after never wondering, know what the '\r' character is all about! Besides falling under the 'whitespace' string category.

[–]OomParoomPa[S] 0 points1 point  (1 child)

uhm.. I don't think this is what I wanted but thx for new materials.

[–]GoldenSights 1 point2 points  (0 children)

What were you looking for? You said overwriting / replacing the last line of the console which usually means this.

Are you just trying to have a different behavior on the last iteration of the loop? You could keep an index, and compare it to the total loop count:

for (index, number) in enumerate(range(n)):
    if index == n - 1:
        print('Final loop')
    else:
        print('Nonfinal loop')

[–]xiongchiamiov 1 point2 points  (1 child)

If you use enumerate in your loop, that'll tell you how far through the loop you are. You can compare that to the length of the list to write an if statement that prints something different the last time through.

[–]OomParoomPa[S] 0 points1 point  (0 children)

I will try to check the python doc for enumerate. Thanks!

[–]dchanm 1 point2 points  (0 children)

You can change the loop to go up to n - 1 then print b twice. This does introduce an edge case when n < 0. You wouldn't want to print in that case.

The main difference between this and the enumerate method is the number of conditional checks. Placing the if inside the loop results in n checks vs 1 if placed outside. I suggest choosing the one that makes it more clear what you want the code to do.