kwlist = [
#--start keywords--
'False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield',
#--end keywords--
]
可以看到,在 keyword.kwlist 这张列表中一共定义了 35 个关键字。
在接下来的例子中,我们将会由用户随意输入一个字符串,然后使用 keyword 库判断其是否是一个关键字。
# Python – Check if given String is Keyword
import keyword
if __name__ == '__main__':
# read string from user
s = input("Enter a string: ")
# check if the string is a keyword
iskey = keyword.iskeyword(s)
print('Is', s, 'a keyword:', iskey)
多次执行并输出结果:
D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe D:/PycharmProjects/MyPythonApp/testkeywords.py
Enter a string: pop
Is pop a keyword: False
D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe D:/PycharmProjects/MyPythonApp/testkeywords.py
Enter a string: print
Is print a keyword: False
D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe D:/PycharmProjects/MyPythonApp/testkeywords.py
Enter a string: for
Is for a keyword: True
D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe D:/PycharmProjects/MyPythonApp/testkeywords.py
Enter a string: true
Is true a keyword: False
D:\PycharmProjects\MyPythonApp\venv\Scripts\python.exe D:/PycharmProjects/MyPythonApp/testkeywords.py
Enter a string: yield
Is yield a keyword: True
在接下来的例子中,我们将要使用 kwlist 属性获取 Python 关键字列表,并使用 for 循环将所有关键字打印出来:
# Example – Get all Python Keywords programmatically
import keyword
import sys
if __name__ == '__main__':
print('All keywords of Python', sys.version, ':')
# get all keywords
keywords = keyword.kwlist
# print the keywords
for key in keywords:
print(key)
执行和输出:
All keywords of Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] :
False
None
True
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield