[英]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))
I got used to writing simple code using this method however, I've been told this is the python2 method and will no longer be supported in the upcoming future when new versions of python are released.我习惯于使用这种方法编写简单的代码,但是,有人告诉我这是 python2 方法,在未来发布新版本的 python 时将不再支持。 what would be the new way to write this loop?
编写此循环的新方法是什么? Thank you
谢谢
The newest way in python3
would be with [f-strings][1] where each {}
is a placeholder for a statement(a variable, an expresion, etc) . python3
的最新方法是使用 [f-strings][1] ,其中每个{}
是语句(变量、表达式等)的占位符。 For example:例如:
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.