如何在 Python3 中像 printf 一样打印? [英] How to print like printf in Python3?

查看:53
本文介绍了如何在 Python3 中像 printf 一样打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2 中我使用:

In Python 2 I used:

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

我试过了:

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

推荐答案

在 Python2 中,print 是引入语句的关键字:

In Python2, print was a keyword which introduced a statement:

print "Hi"

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

In Python3, print is a function which may be invoked:

print ("Hi")

在两个版本中,% 都是一个运算符,它需要左侧的字符串和一个值或一组值或一个映射对象(如 dict) 在右侧.

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

此外,对于 Python3 及更新版本的建议是使用 {}-style 格式而不是 %-style 格式:

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 引入了另一种字符串格式化范例:f-strings.

Python 3.6 introduces yet another string-formatting paradigm: f-strings.

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

这篇关于如何在 Python3 中像 printf 一样打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆