如何在Python3中打印格式化字符串?

21

嘿,我有一个关于这个的问题

print ("So, you're %r old, %r tall and %r heavy.") % (
    age, height, weight)

这行代码在Python 3.4中不起作用,有人知道怎么修复吗?

6个回答

40

当然可以,但是原帖中使用的是Python 3.4版本。 - Martijn Pieters

18

你需要将格式应用于字符串,而不是 print() 函数的返回值:

print("So, you're %r old, %r tall and %r heavy." % (
    age, height, weight))

请注意)闭合括号的位置。如果这能帮助您理解差异,请先将格式化操作的结果分配给一个变量:

output = "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
print(output)

你可以尝试使用 str.format() 或者如果你能升级到 Python 3.6 或者更新版本,就可以使用格式化的字符串字面值(也被称为 f-strings)。

如果你只需要在代码中打印或创建字符串,可以使用 f-strings。如果你需要多次使用相同的模板字符串并插入不同的值,则应该使用 str.format()。这两种方法都可以更轻松地避免在代码中出现混淆。

f-stringsstr.format() 中,如果想要输出 repr() 函数的返回值,可以在字段后加上 !r,效果与 %r 相同:

print("So, you're {age!r} old, {height!r} tall and {weight!r} heavy.")

或者使用带有位置占位符的模板:

template = "So, you're {!r} old, {!r} tall and {!r} heavy."
print(template.format(age, height, weight)

11

您写道:

print("So, you're %r old, %r tall and %r heavy.") % (age, height, weight)

当正确时:

print("So, you're %r old, %r tall and %r heavy." % (age, height, weight))

此外,你应该考虑切换到“新”的.format风格,这更符合Python的编程风格,而且不需要类型声明。它从Python 3.0开始使用,但也适用于2.6+。

print("So, you're {} old, {} tall and {} heavy.".format(age, height, weight))
#or for pinning(to skip the variable expanding if you want something 
#specific to appear twice for example)
print("So, you're {0} old, {1} tall and {2} heavy and {1} tall again".format(age, height, weight))

或者如果您只想使用Python 3.6+的格式化:

print(f"So, you're {age} old, {height} tall and {weight} heavy.")

4

虽然我不知道你遇到了哪个异常,但是你可以尝试使用format函数:

print ("So, you're {0} old, {1} tall and {2} heavy.".format(age, height, weight))

正如其他答案中提到的,你显然在括号上遇到了一些问题。

如果你想使用format,我仍然会把我的解决方案留下来作为参考。


2

您的语法有问题,靠近...) % ( age, height, weight)

%运算符之前,您已经关闭了print,这就是为什么print函数不会携带您传递给它的参数。 在您的代码中只需按照以下方式操作即可:

print ("So, you're %r old, %r tall and %r heavy." % (
    age, height, weight))

2

更简单的方法:

print ("So, you're ",age,"r old, ", height, " tall and ",weight," heavy." )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接