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 related to
python
string
python-3.x
print("Name={}, balance={}".format(var-name, var-balance))
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).
Other words printf absent in python... I'm surprised! Best code is
def printf(format, *args):
sys.stdout.write(format % args)
Because of this form allows not to print \n. All others no. That's why print is bad operator. And also you need write args in special form. There is no disadvantages in function above. It's a standard usual form of printf function.
A simpler one.
def printf(format, *values):
print(format % values )
Then:
printf("Hello, this is my name %s and my age %d", "Martin", 20)
Simple Example:
print("foo %d, bar %d" % (1,2))
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
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))
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.
Source: Stackoverflow.com