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

Is there any Pythonic way?

1 Answer

0 votes
by (25.1k points)

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

...