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

问题描述 投票:1回答:6

嘿,我有一个问题

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

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

python string python-3.x
6个回答
10
投票

在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


7
投票

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

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

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

1
投票

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

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

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

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


1
投票

更简单的方法:

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

0
投票

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

你已经在qazxsw poi运营商之前关闭了qazxsw poi。这就是为什么print函数不会携带你传递的参数。在你的代码中这样做,

%
© www.soinside.com 2019 - 2024. All rights reserved.