How to print like printf in Python3?

PythonStringPython 3.x

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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}')

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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.

Solution 5 - Python

Simple Example:

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

Solution 6 - Python

A simpler one.

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

Then:

printf("Hello, this is my name %s and my age %d", "Martin", 20)

Solution 7 - Python

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

Solution 8 - Python

print("Name={}, balance={}".format(var-name, var-balance))

Solution 9 - Python

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)

Solution 10 - Python

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

Formatting helpful in situations like these.

You can refer to further details in the link below.

Python Formatting

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike LView Question on Stackoverflow
Solution 1 - PythonRobᵩView Answer on Stackoverflow
Solution 2 - PythonthefourtheyeView Answer on Stackoverflow
Solution 3 - Pythonstackoverflowuser2010View Answer on Stackoverflow
Solution 4 - Pythonkva1966View Answer on Stackoverflow
Solution 5 - PythonDonald DerekView Answer on Stackoverflow
Solution 6 - PythonFamory ToureView Answer on Stackoverflow
Solution 7 - PythonkindallView Answer on Stackoverflow
Solution 8 - PythonUser707View Answer on Stackoverflow
Solution 9 - PythonodaView Answer on Stackoverflow
Solution 10 - PythonJoel SathiyendraView Answer on Stackoverflow