How to print like printf in Python3?

132

In Python 2 I used:

print "a=%d,b=%d" % (f(x,n),g(x,n))

I've tried:

print("a=%d,b=%d") % (f(x,n),g(x,n))

This question is tagged with python string python-3.x

~ Asked on 2013-10-18 19:03:03

The Best Answer is


218

In Python2, print was a keyword which introduced a statement:

print "Hi"

In Python3, print is a function which may be invoked:

print ("Hi")

In both versions, % is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict) on the right-hand side.

So, your line ought to look like this:

print("a=%d,b=%d" % (f(x,n),g(x,n)))

Also, the recommendation for Python3 and newer is to use {}-style formatting instead of %-style formatting:

print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))

Python 3.6 introduces yet another string-formatting paradigm: f-strings.

print(f'a={f(x,n):d}, b={g(x,n):d}')

~ Answered on 2013-10-18 19:04:19


54

The most recommended way to do is to use format method. Read more about it here

a, b = 1, 2

print("a={0},b={1}".format(a, b))

~ Answered on 2013-10-18 19:06:12


Most Viewed Questions: