什么不能分配给python中的字面意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32035823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what does can't assign to literal mean in python?
提问by The impossible girl
I have been writing programs in python, but then it comes up with can't assign to literal, What does it mean? and What causes it? I've searched to try and find this but I can't find it.
我一直在用python编写程序,但后来出现了无法分配给文字的问题,这是什么意思?是什么原因造成的?我已经搜索试图找到这个,但我找不到它。
回答by unutbu
The object on the left-hand side of an assignment statement can not be a literal. A literalis a string, number, tuple, list, dict, boolean, or None
. For example, all these raise SyntaxError: can't assign to literal
:
赋值语句左侧的对象不能是文字。文字是字符串、数字、元组、列表、字典、布尔值或None
. 例如,所有这些都提高了SyntaxError: can't assign to literal
:
>>> 'foo' = 1
>>> 5 = 1
>>> [1, 2] = 3
This SyntaxError can also happen through an indirect assignment:
这种 SyntaxError 也可以通过间接赋值发生:
>>> for 'foo' in [1,2,3]:
.... pass
SyntaxError: can't assign to literal
In the for-loop, Python tries to assign the values 1, 2, 3 to the literal string 'foo'
, which raises the SyntaxError.
在 for 循环中,Python 尝试将值 1、2、3 分配给文字 string 'foo'
,这会引发 SyntaxError。
The fix, of course, is to supply a variable name such as foo
, not the string, 'foo'
:
当然,修复方法是提供一个变量名,例如foo
,而不是字符串'foo'
:
for foo in [1,2,3]:
pass