Python2 中的 Python3 f 字符串替代

我主要使用 Python3。我可以写这个吗

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

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

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


ITMISS
浏览 320回答 3
3回答

慕村9548890

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

倚天杖

有两种方法>>> "The number is %d" % (21+21)'The number is 42'>>> "The number is {}".format(21+21)'The number is 42'

DIEA

实际上,您可以使用 .format() 方法来提高可读性,它是 f 字符串的来源。您可以使用:print("the answer is {}!".format(21+21))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python