0
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?

2
  • Or unpack a dictionary "..."..format(**{"10cats": s1*10}) Commented Dec 3, 2014 at 13:02
  • 3
    It's kind of weird to have numbers in your variable names at all. What if your boss comes in tomorrow and says "good job on the cat project, but we need to increase max cat-capacity from 10 to 20". Now you have to replace your _10cats variable everywhere with _20cats. Commented Dec 3, 2014 at 13:04

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.