Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print on same line at the first in python 2 and 3

There are several solutions for printing on same line and at the first of it, like below.

In python 2,

print "\r Running... xxx",

And in Python 3,

print("\r Running... xxx", end="")

I can't find a single print solution to cover python 2 and 3 at the same time. Do I have to use sys.stdout.write?

like image 349
lqez Avatar asked Jul 14 '14 08:07

lqez


People also ask

How do I print the same line in Python 2?

If you want to print your text on the same line in Python 2, you should use a comma at the end of your print statement. Here's an example of this in action: print "Hello there!", print "It is a great day."

How do you print a list of elements on the same line in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.

How do you combine print and input on the same line in Python?

How to print() and input() on the same line in Python # Pass a string to the input() function to have a print statement and input on the same line, e.g. username = input('Enter your username: ') . The input() function takes a prompt string and prints it to standard output without a trailing newline.


2 Answers

Use from __future__ import print_function and use the print() function in both Python 2 and Python 3:

from __future__ import print_function

print("\r Running... xxx", end="")  # works across both major versions

See the print() function documentation in Python 2:

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from __future__ import print_function

The print() function was added to Python 2.6.

like image 87
Martijn Pieters Avatar answered Sep 22 '22 15:09

Martijn Pieters


Use

from __future__ import print_function

in Python 2 and use print as a function in Python 2 also

print("\r Running... xxx", end="")
like image 41
thefourtheye Avatar answered Sep 18 '22 15:09

thefourtheye