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

Sox*_*xty 8 python string python-3.x

嘿,我有一个问题

print ("So, you're %r old, %r tall and %r heavy.") % (
    age, height, weight)
Run Code Online (Sandbox Code Playgroud)

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

小智 20

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

你可以这样写

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

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


Mar*_*ers 11

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

print("So, you're %r old, %r tall and %r heavy." % (
    age, height, weight))
Run Code Online (Sandbox Code Playgroud)

请注意)右括号的位置.如果它可以帮助您理解差异,请首先将格式化操作的结果分配给变量:

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


Joh*_*los 8

你写:

print("So, you're %r old, %r tall and %r heavy.") % (age, height, weight)
Run Code Online (Sandbox Code Playgroud)

当正确的是:

print("So, you're %r old, %r tall and %r heavy." % (age, height, weight))
Run Code Online (Sandbox Code Playgroud)

除此之外,你应该考虑切换到"新".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))
Run Code Online (Sandbox Code Playgroud)


Vis*_*yay 2

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

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

print ("So, you're %r old, %r tall and %r heavy." % (
    age, height, weight))
Run Code Online (Sandbox Code Playgroud)