165

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))
MadHatter
  • 366
  • 1
  • 7
  • 23
Mike L
  • 1,955
  • 2
  • 16
  • 18
  • 12
    `%` has always been a string operator, not related to the `print` statement. You could, for example, create a string with `s="a=%d,b=%d"%(f(x,n),g(x,n))`, then print that string with `print s`. – chepner Oct 18 '13 at 19:18

10 Answers10

259

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}')
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 18
    *or:* `print('a={first:4.2f}, b={second:03d}'.format(first=f(x,n),second=g(x,n)))` where this example shows how you can use the printf-style modifiers *and* still use keywords. – fbicknel May 01 '14 at 13:47
  • 2
    @rapt, it has some huge advantages. Not the least of which is you can reference the same format only multiple times or out of order: "{1}, {1}, {0}, and {1} ".format("eggs","spam")=="spam, spam, eggs, and spam" – Dr Xorile Feb 12 '18 at 14:45
68

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))
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
46

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14
Quasímodo
  • 3,812
  • 14
  • 25
stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
33

Python 3.6 introduced f-strings for inline interpolation. What's even nicer is it extended the syntax to also allow format specifiers with interpolation. Something I've been working on while I googled this (and came across this old question!):

print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')

PEP 498 has the details. And... it sorted my pet peeve with format specifiers in other langs -- allows for specifiers that themselves can be expressions! Yay! See: Format Specifiers.

kva1966
  • 611
  • 6
  • 8
18

Simple Example:

print("foo %d, bar %d" % (1,2))

Donald Derek
  • 2,529
  • 2
  • 23
  • 17
11

A simpler one.

def printf(format, *values):
    print(format % values )

Then:

printf("Hello, this is my name %s and my age %d", "Martin", 20)
user247702
  • 23,641
  • 15
  • 110
  • 157
Famory Toure
  • 111
  • 1
  • 2
3
print("Name={}, balance={}".format(var-name, var-balance))
User707
  • 182
  • 2
  • 8
3

You can literally use printf in Python through the ctypes module (or even your own C extension module).

On Linux, you should be able to do

import ctypes

libc = ctypes.cdll.LoadLibrary("libc.so.6")
printf = libc.printf
printf(b"Integer: %d\n"
       b"String : %s\n"
       b"Double : %f (%%f style)\n"
       b"Double : %g      (%%g style)\n",
       42, b"some string", ctypes.c_double(3.20), ctypes.c_double(3.20))

On Windows, the equivalent would have

libc = ctypes.cdll.msvcrt
printf = libc.printf

As stated in the documentation:

None, integers, bytes objects and (unicode) strings are the only native Python objects that can directly be used as parameters in these function calls. None is passed as a C NULL pointer, bytes objects and strings are passed as pointer to the memory block that contains their data (char* or wchar_t*). Python integers are passed as the platforms default C int type, their value is masked to fit into the C type.

This explains why I wrapped the Python float objects using ctypes.c_double (FYI, a Python float is typically a double in C).

Output

Integer: 42
String : some string
Double : 3.200000 (%f style)
Double : 3.2      (%g style)
OTheDev
  • 2,916
  • 2
  • 4
  • 20
2

Because your % is outside the print(...) parentheses, you're trying to insert your variables into the result of your print call. print(...) returns None, so this won't work, and there's also the small matter of you already having printed your template by this time and time travel being prohibited by the laws of the universe we inhabit.

The whole thing you want to print, including the % and its operand, needs to be inside your print(...) call, so that the string can be built before it is printed.

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

I have added a few extra spaces to make it clearer (though they are not necessary and generally not considered good style).

kindall
  • 178,883
  • 35
  • 278
  • 309
-2

print("{:.4f} @\n".format(2))

Formatting helpful in situations like these.

You can refer to further details in the link below.

Python Formatting