我可能偶然发现了非法的变量名称
pass = "Pass the monkey!"
print pass
语法错误:语法无效
我知道有些关键词是作为变量而禁止的。 Pythonic是否等同于JavaScript variable name validator?
答案 0 :(得分:8)
您可以使用keyword模块
来测试某些内容是否为关键字account id
https://docs.python.org/2/library/keyword.html
此模块允许Python程序确定字符串是否为a 关键字。
<强> keyword.iskeyword(S)强>
如果s是Python关键字,则返回true。
答案 1 :(得分:3)
某些变量名称在Python中是非法的,因为它是保留字。
来自Python文档中的keywords
section:
以下标识符用作保留字或关键字 语言,不能用作普通标识符。他们 必须完全按照这里所写的拼写:
# Complete list of reserved words
and
del
from
not
while
as
elif
global
or
with
assert
else
if
pass
yield
break
except
import
print
class
exec
in
raise
continue
finally
is
return
def
for
lambda
try
True # Python 3 onwards
False # Python 3 onwards
None # Python 3 onwards
nonlocal # Python 3 onwards
async # in Python 3.7
await # in Python 3.7
因此,您不能将上述任何标识符用作变量名。
答案 2 :(得分:2)