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

时间:2014-11-11 10:32:24

标签: python string python-3.x

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

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

该行在python 3.4中不起作用。有人知道如何解决这个问题吗?

6 个答案:

答案 0 :(得分:9)

在Python 3.6中引入了f字符串。

你可以这样写

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

有关更多信息,请参见:https://docs.python.org/3/whatsnew/3.6.html

答案 1 :(得分:6)

您需要将格式应用于字符串,而不是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)

答案 2 :(得分:5)

你写道:

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

除此之外,你应该考虑切换到更新pythonic并且不需要声明类型声明的“new”.format样式。从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))

答案 3 :(得分:1)

即使我不知道你得到了哪个例外,你也可以尝试使用格式化功能:

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

正如其他答案中所提到的,你的括号显然有些问题。

如果您想使用format,我仍会将我的解决方案作为参考。

答案 4 :(得分:0)

...) % ( age, height, weight)附近的语法有问题。

您已关闭print brfore %运营商。这就是为什么print函数不会携带你传递的参数的原因。 在你的代码中这样做,

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

答案 5 :(得分:0)

更简单的方法:

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