-2

I'd like to print at same line for print statement inside a for loop using end= parameter. not sure which end parameter i can use.

For example, in below, for each time's print, only need to change str(i) and str(result), everything is the same.

for i in range(10):
   result=i**2
   print('iteration is'+str(i)+' with result of '+str(result))

Thanks

roudan
  • 3,082
  • 5
  • 31
  • 72
  • What do you mean by `not sure which end parameter i can use.`? – tkausl Feb 14 '23 at 18:48
  • 1
    `'\r'` can move back to the start of the line, if that's what you are looking for? – 001 Feb 14 '23 at 18:48
  • `print(my_str, end='')` – SiP Feb 14 '23 at 18:50
  • Thanks Johnny, using '\r' work. here is my new code: for i in range(1000000): result=i+10 print('iteration is '+str(i)+' with result of '+str(result),end='\r'). Can you provide the solution so I can accept it? Thanks – roudan Feb 14 '23 at 18:53
  • 1
    @roudan I think this will cause the next printed line (from somewhere else in the code) to override this print – SiP Feb 14 '23 at 18:56

1 Answers1

1

Use an empty end parameter and go back the length of the previous print

L=0
for i in range(3):
   result=i**2
   my_str = 'iteration is'+str(i)+' with result of '+str(result)
   print('\b'*L + my_str, end='')
   L= len(my_str)
SiP
  • 1,080
  • 3
  • 8
  • 1
    There's no reason to print more than one `\r` (carriage return) here. Maybe you are thinking of `\b` (backspace). – 001 Feb 14 '23 at 19:42
  • @JohnnyMopp, you're right. I was thinking of \b. Thx – SiP Feb 15 '23 at 11:05