在Python 2中,我使用了:
print "a=%d,b=%d" % (f(x,n),g(x,n))
我试过了:
print("a=%d,b=%d") % (f(x,n),g(x,n))
发布于 2013-10-19 03:04:19
在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)))
Python3.6引入了另一个字符串格式化范例:f-strings。
print(f'a={f(x,n):d}, b={g(x,n):d}')
发布于 2013-10-19 03:06:12
最推荐的方法是使用format
方法。阅读有关它的更多信息here
a, b = 1, 2
print("a={0},b={1}".format(a, b))
发布于 2016-06-16 09:19:19
来自O'Reilly's 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
https://stackoverflow.com/questions/19457227
复制相似问题