Python2中的Python3 f字符串替代

时间:2019-04-16 13:20:50

标签: python python-3.x python-2.7 f-string

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

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

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

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

4 个答案:

答案 0 :(得分:6)

使用format

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

答案 1 :(得分:3)

有两种方法

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

答案 2 :(得分:2)

实际上,您可以使用.format()方法进行可读性设置,这是f字符串的来源。

您可以使用:

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

答案 3 :(得分:0)

您可以使用 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'
相关问题