繁体   English   中英

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

[英]How to print formatted string in Python3?

嘿,我对此有疑问

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

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

在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

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

如果您只需要在现场格式化某些内容以打印或出于其他原因创建字符串,请使用f字符串,使用str.format()存储模板字符串以供重复使用,然后插值。 两者都使您不容易混淆print()开始和结束位置以及格式化的位置。

f-stringsstr.format() ,在字段后使用!r以获得repr()输出,就像%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)

你写:

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

或者,如果您只想要python 3.6+格式:

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

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

您已经关闭了print操作符%运算符。 这就是为什么print函数不会携带您要传递的参数的原因。 只需在您的代码中这样做,

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

即使我不知道会遇到哪种异常,也可以尝试使用format函数:

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

如其他答案中所述,您的括号显然有问题。

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

更简单的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM