在 Python 3中如何像 printf 一样打印?

在 Python 2中,我使用:

print "a=%d,b=%d" % (f(x,n),g(x,n))

我试过了:

print("a=%d,b=%d") % (f(x,n),g(x,n))
501242 次浏览

在 Python 2中,print是一个关键字,它引入了一个语句:

print "Hi"

在 Python 3中,print是一个可以被调用的函数:

print ("Hi")

在这两个版本中,%都是一个操作符,它需要在左边显示一个字符串,在右边显示一个值或值元组或映射对象(如 dict)。

所以,你的台词应该是这样的:

print("a=%d,b=%d" % (f(x,n),g(x,n)))

此外,Python 3和更新的版本建议使用 {}样式的格式,而不是 %样式的格式:

print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))

Python 3.6引入了另一种字符串格式化范例: F 弦

print(f'a={f(x,n):d}, b={g(x,n):d}')

最推荐的方法是使用 format方法

a, b = 1, 2


print("a={0},b={1}".format(a, b))

因为您的 %print(...)括号之外,所以您要尝试将变量插入到 print调用的 结果中。print(...)返回 None,所以这不会起作用,还有一个小问题,你已经打印了你的模板到这个时间和时间旅行被我们居住的宇宙法则所禁止。

要打印的所有内容,包括 %及其操作数,都需要是 在里面print(...)调用,以便在打印之前构建字符串。

print( "a=%d,b=%d" % (f(x,n), g(x,n)) )

我已经添加了一些额外的空间,使其更加清晰(虽然他们不是必要的,通常不被认为是好的风格)。

简单的例子:

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

来自 O’Reilly 的 Python 烹饪书的简单 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("Name={}, balance={}".format(var-name, var-balance))

更简单的。

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

然后:

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

Python 3.6为内联插值引入了 f-string。更好的是,它扩展了语法,也允许带插值的格式说明符。我在谷歌搜索这个的时候一直在研究的东西(然后发现了这个老问题!):

print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')

PEP 498 有详细资料。并且... 它用其他语言中的格式说明符来排列我讨厌的东西——允许说明符本身可以是表达式!耶!见: 格式说明书

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

格式化在这种情况下很有帮助。

你可在以下连结查阅详情。

Python 格式化

您可以通过 ctypes模块(甚至您自己的 C 扩展模块)在 Python 中使用 printf

Linux上,你应该能够做

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

窗户上,相当于

libc = ctypes.cdll.msvcrt
printf = libc.printf

文件所述:

无、整数、字节对象和(unicode)字符串是唯一可以直接用作这些函数调用中的参数的本机 Python 对象。没有作为 C NULL 指针传递,字节对象和字符串作为指向包含它们的数据(char * 或 wchar _ t *)的内存块的指针传递。Python 整数作为平台默认的 C int 类型传递,它们的值被屏蔽以适应 C 类型。

这解释了为什么我使用 ctypes.c_double来包装 Python float 对象(仅供参考,Python float通常是 C 中的 double)。

输出

Integer: 42
String : some string
Double : 3.200000 (%f style)
Double : 3.2      (%g style)