How to make multiple prints in the same line in python 3?

Asked

Viewed 2,798 times

-1

I want to know how to make prints to be shown in the same line using python 3. Example:

print('1')
print('2')
1
2

I wanted when python was going to print number 2, number one was erased and 2 appeared on the same line as 1 was before.

I tried to do with a code provided in another question here, but I did not get the expected result.

import sys
import time

for x in range(11):
  print("{}%".format (x))
  sys.stdout.write("\033[F")
  time.sleep(0.1)
  • Please. Do not post your codes as an image. As you saw in the other questions and answers, the site has source code support. For more information, do the [tour], read the [Ask] guide and go to [help].

  • And please check that your terminal has support for such characters. The same code you copied from the other question worked perfectly here: https://i.stack.Imgur.com/Ac7kw.gif

1 answer

5

Python 3 automatically places a line break at the end of print, but you can override with whatever you want it to be by adding the parameter end:

print('1', end='') 
print('2')

Thus the print will end with a string empty instead of a line break and the second print will be rendered shortly afterwards.

  • there is some end parameter that erases what was previously printed?

  • Editing reversed because the new text changed the answer. It is clearly said that it is possible to pass any value as end in function print and later commented that with the empty character the output will be on the same line. The edit reduced the answer information and added redundancy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.