Python2中的Python3 f字符串替代

Mar*_*ann 1 python python-2.7 python-3.x f-string

大多数情况下,我使用Python3。我可以写这个吗

print(f"the answer is {21 + 21} !")
Run Code Online (Sandbox Code Playgroud)

输出:答案是42!但是在Python 2中f字符串不存在。那么这是最好的方法吗?

print("the answer is " + str(21 + 21) + "!")
Run Code Online (Sandbox Code Playgroud)

VnC*_*VnC 6

使用format

print("the answer is {} !".format(21 + 21))


小智 6

有两种方法

>>> "The number is %d" % (21+21)
'The number is 42'
>>> "The number is {}".format(21+21)
'The number is 42'
Run Code Online (Sandbox Code Playgroud)