+4 votes
in Programming Languages by (74.2k points)
How can I check whether a given string is a Python keyword or not?

Is there any Pythonic way?

1 Answer

+1 vote
by (350k points)
selected by
 
Best answer

The Python module "keyword" has function iskeyword(). It can be used to determine whether a string is a Python keyword or not.

Here is an example:

>>> import keyword
>>> str="None"
>>> keyword.iskeyword(str)
True
>>> str="hello"
>>> keyword.iskeyword(str)
False


...