Python 2中的Python 3 f-string替代方案是什么?

6
大多数情况下,我使用Python 3。我可以这样写:

print(f"The answer is {21 + 21}!")

输出:

答案是42!

但在Python 2中,f-strings不存在。那么以下方式是否是最佳方法?

print("the answer is " + str(21 + 21) + "!")

1
format 存在于 2.7 版本中。 - roganjosh
a = 21 + 21 print("答案是 {}".format(a)) - vb_rises
4个回答

11

使用format

print("答案是{}!".format(21 + 21))


5

有两种方法

>>> "The number is %d" % (21+21)
'The number is 42'
>>> "The number is {}".format(21+21)
'The number is 42'

3
实际上,你可以使用.format()方法来提高可读性,这也是f-string的来源。
你可以使用:
print("the answer is {}!".format(21+21))

3
你可以使用 fstring 库。

pip install fstring

>>> from fstring import fstring as f
>>> a = 4
>>> b = 5
>>> f('hello result is {a+b}')
u'hello result is 9'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接