How to check if a string is a keyword in Python
We use the iskeyword method to check if a string is a valid Python keyword.
The iskeyword method is available in the keyword module.
What is a
keyword?Every programming language has reserved words known as
keywords. They hold a special use and meaning. For example,classis akeywordthat is used to create aclassin Python.
Syntax
import keyword
keyword.iskeyword(string_to_check)
The iskeyword method returns True if the passed argument is a valid Python keyword; otherwise, it returns False.
Code
import keywordstring = "class"print(string, " :", keyword.iskeyword(string))string = "break"print(string, " :", keyword.iskeyword(string))string = "continue"print(string, " :", keyword.iskeyword(string))string = "test"print(string, " :", keyword.iskeyword(string))string = "python"print(string, " :", keyword.iskeyword(string))
Explanation
In the code above, we imported the keyword module and used the iskeyword method to check if the string is a valid Python keyword.
-
The
class,break, andcontinuestrings are valid Python keywords, soTrueis returned. -
The
testandpythonstrings are not valid Python keywords, soFalseis returned.