0

I like to print something and then replace it with the next value in a way that the previus value will disapear and the new one will replace that. How should I do that? e.g. in

print('Hello World')

for i in range(10):
    print('Case Number {} ...'.format(i)) # I like to print with replacement here

print('Good Bye')

I like to have the final output like this:

Hello World
Case Number 9
Good Bye

P.S. I saw Link but it is not giving me answer print('Case Number {} ...'.format(i), end='\r') does not working for some reason. Specifically:

print('Hello World')

for i in range(10):
    print('Case Number {} ...'.format(i), end='\r') # I like to print with replacement here

print('Good Bye')

will generate:

Hello World
Good Byeber 9 ...
Albert
  • 184
  • 3
  • 3
  • 14
  • You can print `"\r"` (or send it to `sys.stdout`) to return to the start of the line, but you'll need to run your code in the terminal to see this... – Ed Ward Feb 20 '20 at 20:47
  • What do you mean by "does not working for some reason"? Does it raise an error? Does it fail to reset the cursor? – MisterMiyagi Feb 20 '20 at 20:49
  • 1
    The reason you get that output is because "Good Bye" is printed on the same line... Use `print("\nGood bye")` instead... – Ed Ward Feb 20 '20 at 20:51
  • 1
    If you want to print on a new line *after* preparing to overwrite the current line, you must print an explicit newline (``\n``) first. – MisterMiyagi Feb 20 '20 at 20:52
  • I see @EdWard, \n does the magic – Albert Feb 20 '20 at 20:54

1 Answers1

0

Print an extra new line after you're doing with all your in-place rewrites:

print('Hello World')

for i in range(10):
    print('Case Number {} ...'.format(i), end='\r') # I like to print with replacement here

print()  # Move to next line
print('Good Bye')  # Now print

Instead of an empty print, you could just prepend the string in the final print with a newline (\n), making it:

print('\nGood Bye')

but the isolated print() is a little clearer about intent, and doesn't require mucking with constants or string formatting or the like.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271