-5

I have a program that has to only print data onto one line.

What can I do to do this.

for i in range(10):
    print(i)

Is it possible to print all of this on one line so it prints 0, erases the line, print 2, erases, etc..?

PyProg
  • 65
  • 1
  • 2
  • 5

4 Answers4

5

Use print(i,end="\r") to return to the start of the line and overwrite.

clubby789
  • 2,543
  • 4
  • 16
  • 32
3
for i in range(10):
    print(i,end=" ")

this is easiest way to print in one line.

Jainil Patel
  • 1,284
  • 7
  • 16
1

For this specific usecase you can do something like this:

print(*range(10))

And to update each character on the line you will need to use '\r' or the return character, that returns the position of the cursor to the beginning of the line. However, you need to be sure you count in the length of the strings you are printing, otherwise you will be overwriting only part of the string. A full proof solution will be:

import time
maxlen = 0
for i in range(12,-1,-1):
  if len(str(i))>maxlen:
    maxlen = len(str(i))
  print(f'\r{str(i): <{maxlen}}',end = '')
  time.sleep(2)
print('')

time part is added so that you can view the change. maxlen computes the maximum length string you are going to print and formats the string accordingly. Note: I have used f'strings, hence it would only work for Python 3.x

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
1

in python 2.x:

from __future__ import print_function
for i in range(10):
    print (i, end="")

in python 3.x

for i in range(10):
    print (i, end="")
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34