简体   繁体   中英

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. 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) . 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM