How to print two things on the same line python

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first and then I print [DONE].

However, I now want to print Installing xxx... and [DONE] on the same line.

Any ideas?

ivanleoncz

7,9174 gold badges53 silver badges48 bronze badges

asked Apr 8, 2011 at 16:38

2

Python 3 Solution

The print() function accepts an end parameter which defaults to \n (new line). Setting it to an empty string prevents it from issuing a new line at the end of the line.

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

Python 2 Solution

Putting a comma on the end of the print() line prevents print() from issuing a new line (you should note that there will be an extra space at the end of the output).

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

Wouter

5242 gold badges11 silver badges21 bronze badges

answered Apr 8, 2011 at 16:56

7

You can simply use this:

print 'something',
...
print ' else',

and the output will be

something else

no need to overkill by import sys. Pay attention to comma symbol at the end.

Python 3+ print("some string", end=""); to remove the newline insert at the end. Read more by help(print);

answered Mar 14, 2013 at 13:35

boldnikboldnik

2,4792 gold badges25 silver badges32 bronze badges

9

You should use backspace '\r' or ('\x08') char to go back on previous position in console output

Python 2+:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

This code will count from 0% to 100% on one line. Final value will be:

> python test.py
100%

Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?

How to print two things on the same line python

Tropilio

1,2981 gold badge7 silver badges26 bronze badges

answered Mar 31, 2014 at 8:57

Vadim Zin4ukVadim Zin4uk

1,66621 silver badges17 bronze badges

3

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.

How to print two things on the same line python

mgilson

288k60 gold badges601 silver badges674 bronze badges

answered Apr 8, 2011 at 16:42

ferostarferostar

7,0367 gold badges36 silver badges61 bronze badges

1

Most simple:

Python 3

    print('\r' + 'something to be override', end='')

It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.

answered Nov 6, 2018 at 19:15

SunfloroSunfloro

6801 gold badge8 silver badges11 bronze badges

2

None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

To test it:

import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')

"hello " will first print out and flush to the screen before the sleep. After that you can use standard print.

answered Jul 22, 2013 at 18:23

hyprnickhyprnick

2,5732 gold badges20 silver badges18 bronze badges

1

Python appends newline as an end to print. Use end=' ' for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.

print('Foo', end=' ')
print('Bar')

How to print two things on the same line python

Pikamander2

6,2933 gold badges42 silver badges63 bronze badges

answered Dec 24, 2019 at 0:29

MrKulliMrKulli

71910 silver badges18 bronze badges

This simple example will print 1-10 on the same line.

for i in range(1,11):
    print (i, end=" ")

answered May 15, 2018 at 7:01

How to print two things on the same line python

Print has an optional end argument, it is what printed in the end. The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")

How to print two things on the same line python

kaya3

42.5k4 gold badges53 silver badges85 bronze badges

answered Feb 27, 2015 at 16:44

TulkinRBTulkinRB

5901 gold badge6 silver badges10 bronze badges

1

If you want to overwrite the previous line (rather than continually adding to it), you can combine \r with print(), at the end of the print statement. For example,

from time import sleep

for i in xrange(0, 10):
    print("\r{0}".format(i)),
    sleep(.5)

print("...DONE!")

will count 0 to 9, replacing the old number in the console. The "...DONE!" will print on the same line as the last counter, 9.

In your case for the OP, this would allow the console to display percent complete of the install as a "progress bar", where you can define a begin and end character position, and update the markers in between.

print("Installing |XXXXXX              | 30%"),

answered Oct 9, 2015 at 16:18

Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn't make use of the integer argument and could probably be done away with altogether.

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

Both have been tested and work.

answered Jan 10, 2018 at 19:47

DannidDannid

1,34116 silver badges17 bronze badges

This is a very old thread, but here's a very thorough answer and sample code.

\r is the string representation of Carriage Return from the ASCII character set. It's the same as octal 015 [chr(0o15)] or hexidecimal 0d [chr(0x0d)] or decimal 13 [chr(13)]. See man ascii for a boring read. It (\r) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It's the CR part of CRLF which means Carriage Return and Line Feed.

print() is a function in Python 3. In Python 2 (any version that you'd be interested in using), print can be forced into a function by importing its definition from the __future__ module. The benefit of the print function is that you can specify what to print at the end, overriding the default behavior of \n to print a newline at the end of every print() call.

sys.stdout.flush tells Python to flush the output of standard output, which is where you send output with print() unless you specify otherwise. You can also get the same behavior by running with python -u or setting environment variable PYTHONUNBUFFERED=1, thereby skipping the import sys and sys.stdout.flush() calls. The amount you gain by doing that is almost exactly zero and isn't very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.

And a sample. Note that this runs perfectly in Python 2 or 3.

from __future__ import print_function

import sys
import time

ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}

for i in range(1, ANS + 1):
    if i in FACTORS:
        print('\r{0:d}'.format(i), end='')
        sys.stdout.flush()
        time.sleep(ANS / 100.0)
else:
    print()

answered Oct 25, 2017 at 18:20

1

This solution in Python 3.X specific:

When I need to do this, I'll generally just use

end=' '

For example:

# end='' ends the output with a  
print("Welcome to" , end = ' ') 
print("stackoverflow", end = ' ')

This outputs as:

Welcome to stackoverflow

The space in end= can be replaced with any character. For example,

print("Welcome to" , end = '...') 
print("stackoverflow", end = '!')

Which outputs as:

Welcome to...stackoverflow!

How to print two things on the same line python

Dharman

27.8k21 gold badges75 silver badges126 bronze badges

answered Jul 22, 2021 at 19:39

alioalio

1046 bronze badges

print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")

Ryan Lee

1971 silver badge8 bronze badges

answered Jul 23, 2019 at 22:35

How to print two things on the same line python

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],

answered Oct 16, 2016 at 23:20

Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).

The example they provide:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

For printing the on the same line, as others have suggested, just use end=""

answered Nov 14, 2019 at 18:15

MirceaMircea

9241 gold badge13 silver badges17 bronze badges

I found this solution, and it's working on Python 2.7

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms

How to print two things on the same line python

ideasman42

37.2k33 gold badges177 silver badges293 bronze badges

answered Dec 7, 2016 at 12:51

Luis SilvaLuis Silva

91 silver badge3 bronze badges

1

How do I print two statements on the same line?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.

How do you print on the same line in Python?

Use a carriage return "\r" to print over the same line Use the syntax print(string, end = "\r") to make the next stdout line begin at the beginning of the current line.

How do you print side by side in Python?

Using "end" Argument in the print statement (Python 3. X) In Python 3, print() is a function that prints output on different lines, every time you use the function. ... .
Using "sys" Library (Python 3. X) to Print Without Newline. ... .
Using "comma" to Terminate Print Statement. In order to print in the same line in Python 2..

How do you print on the same line in Python without space?

To print without a new line in Python 3 add an extra argument to your print function telling the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') The next print function will be on the same line.