Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

python - SyntaxError invalid token

I have a problem when I try to assign a value to a variable. The problem shows up when I try to put a date as a tuple or a list in this order: year, month, day.

>>> a = (2016,04,03)         # I try to put the date into variable 'a' as a tuple.
SyntaxError: invalid token
>>> a = [2016,04,03]         # I try to put the date into variable 'a' as a list.
SyntaxError: invalid token
  1. Why is this happing?

  2. How do I fix it?

  3. What does token mean in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Python 3, leading zeros are not allowed on numbers. E.g:

05
0123

Etc. are not allowed, but should be written as 5 and 123 instead.

In Python 2, however, the leading zero signifies that the number is an octal number (base eight), so 04 or 03 would mean 4 and 3 in octal, respectively, but 08 would be invalid as it is not a valid octal number.

In Python 3, the syntax for octals changed to this:

0o10
0o4

(As well as allowing other bases such as binary and hexadecimal using the 0b or 0x prefixes.)

As for your other question, a token in Python is the way the Python interpreter splits up your code into chunks, so that it can understand it (see here). Here, when the tokenizer tries to split up your code it doesn't expect to see the zero there and so throws an error.

I would suggest (similarly to the other answers) that you drop the leading zero ((2016,4,3)) or represent these using strings (("2016","04","03")).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...