Answers:
在Python2中,print
是一个引入了以下语句的关键字:
print "Hi"
在Python3中,print
是可以调用的函数:
print ("Hi")
在这两个版本中,%
都是一个运算符,它在左侧需要一个字符串,在右侧需要一个值或一个值的元组或一个映射对象(如dict
)。
因此,您的行应如下所示:
print("a=%d,b=%d" % (f(x,n),g(x,n)))
另外,对于Python3和更高版本,建议使用{}
-style格式而不是%
-style格式:
print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))
Python 3.6引入了另一种字符串格式范例:f-strings。
print(f'a={f(x,n):d}, b={g(x,n):d}')
print('a={first:4.2f}, b={second:03d}'.format(first=f(x,n),second=g(x,n)))
此示例显示了如何使用printf样式修饰符并仍使用关键字。
来自O'Reilly的Python Cookbook的简单printf()函数。
import sys
def printf(format, *args):
sys.stdout.write(format % args)
输出示例:
i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14
PRINT
和FORMAT
...?时光
%
一直是字符串运算符,与print
语句无关。例如,您可以使用创建一个字符串s="a=%d,b=%d"%(f(x,n),g(x,n))
,然后使用来打印该字符串print s
。