简体   繁体   中英

python string formatting using .format and variable

s1 = "cats"

print "are 10 cats {}" .format(s1*10) 
print "are 10 cats {10cats}" .format(10cats=s1*10)

First print works, second I get SyntaxError: invalid syntax . Why?

Variable names in python (and many other languages) cannot start with numbers . If you used a legal variable name, the second would work fine.

>>> s1 = "cats"
>>> print("are 10 cats {cats}" .format(cats=s1*10))
are 10 cats catscatscatscatscatscatscatscatscatscats

As stated already, variable names in Python cannot start with numbers. Additionally, there are other characters that cannot be used in variable names in Python.

http://www.pasteur.fr/formation/infobio/python/ch02s03.html

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