簡體   English   中英

Python2 中的 Python3 f 字符串替代

[英]Python3 f string alternativ in Python2

我主要使用 Python3。 我可以寫這個嗎

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

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

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

使用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'

實際上,您可以使用.format()方法來提高可讀性,這是f字符串的來源。

您可以使用:

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

您可以使用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM