简体   繁体   English

使用.format和变量的python字符串格式化

[英]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 . 第一次print有效,第二次我得到SyntaxError: invalid syntax Why? 为什么?

Variable names in python (and many other languages) cannot start with numbers . python(和许多其他语言)中的变量名称不能以number开头 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. 如前所述,Python中的变量名不能以数字开头。 Additionally, there are other characters that cannot be used in variable names in Python. 此外,还有其他一些字符不能在Python的变量名中使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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