[英]How would I write this for loop written in Python 2 known as string interpolation into syntax for python3?
for i in range(1, 12):
print("no {} squared is {} and cubed is {:4}".format(i, i**2, i**4))
我習慣於使用這種方法編寫簡單的代碼,但是,有人告訴我這是 python2 方法,在未來發布新版本的 python 時將不再支持。 編寫此循環的新方法是什么? 謝謝
python3
的最新方法是使用 [f-strings][1] ,其中每個{}
是語句(變量、表達式等)的占位符。 例如:
for i in range(1, 12):
print(f"no {i} squared is {i**2} and cubed is {i**4:4}"
>>>
no 1 squared is 1 and cubed is 1
no 2 squared is 4 and cubed is 16
no 3 squared is 9 and cubed is 81
no 4 squared is 16 and cubed is 256
no 5 squared is 25 and cubed is 625
no 6 squared is 36 and cubed is 1296
no 7 squared is 49 and cubed is 2401
no 8 squared is 64 and cubed is 4096
no 9 squared is 81 and cubed is 6561
no 10 squared is 100 and cubed is 10000
no 11 squared is 121 and cubed is 14641
[1]: https://www.python.org/dev/peps/pep-0498/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.