Python关键字列表

35 投票
2 回答
25174 浏览
提问于 2025-04-17 14:09

我正在写一个程序,这个程序需要生成一些Python代码。如果一个字符串是Python的关键字,我需要对它进行特别处理。用help(keywords)这个命令可以打印出Python的关键字和一些额外的信息,但我想知道有没有更“Python风格”的方法,可以直接得到一个包含这些关键字的可迭代对象?

2 个回答

16

你也可以检查一个特定的关键词。

import keyword
keyword.iskeyword("print") # TRUE
80

你最好使用 keyword 这个模块。

>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

撰写回答