+4 votes
in Programming Languages by (73.8k 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 (348k 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)
>>> str="hello"
>>> keyword.iskeyword(str)