How to print like printf in Python3?

Question:

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))
Asked By: Mike L

||

Answers:

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 By: Robᵩ

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 By: thefourtheye

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).

Answered By: kindall

Simple Example:

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

Answered By: Donald Derek

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=%.2fn", i, pi)
# hi there, i=7, pi=3.14
print("Name={}, balance={}".format(var-name, var-balance))
Answered By: User707

A simpler one.

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

Then:

printf("Hello, this is my name %s and my age %d", "Martin", 20)
Answered By: Famory Toure

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.

Answered By: kva1966

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

Formatting helpful in situations like these.

You can refer to further details in the link below.

Python Formatting

Answered By: Joel Sathiyendra

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: %dn"
       b"String : %sn"
       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)
Answered By: oda
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.