How to print formatted string in Python3?
嘿,关于这个我有个问题
1 2 | print ("So, you're %r old, %r tall and %r heavy.") % ( age, height, weight) |
该行在python 3.4中不起作用,有人知道如何解决这个问题吗?
在python 3.6中引入了F字符串。
你可以这样写
1 | print (f"So, you're {age} old, {height} tall and {weight} heavy.") |
有关详细信息,请参阅:https://docs.python.org/3/whatsnew/3.6.html
您需要将格式应用于字符串,而不是
1 2 | print("So, you're %r old, %r tall and %r heavy." % ( age, height, weight)) |
注意
1 2 | output ="So, you're %r old, %r tall and %r heavy." % (age, height, weight) print(output) |
你写:
1 | print ("So, you're %r old, %r tall and %r heavy.") % (age, height, weight) |
当正确的是:
1 | print ("So, you're %r old, %r tall and %r heavy." % (age, height, weight)) |
除此之外,您还应该考虑切换到"new".格式样式,它更像是Python式的,不需要类型声明。从python 3.0开始,但返回到2.6+
1 2 3 4 | 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)) |
正如其他答案中提到的,你的括号显然有些问题。
如果您想使用
更简单的方法:
1 | print ("So, you're",age,"r old,", height," tall and",weight," heavy." ) |
您的语法有问题,在
age, height, weight)
您已经关闭了
1 2 | print ("So, you're %r old, %r tall and %r heavy." % ( age, height, weight)) |