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,class
is akeyword
that is used to create aclass
in Python.
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
.
import keyword string = "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))
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
, and continue
strings are valid Python keywords, so True
is returned.
The test
and python
strings are not valid Python keywords, so False
is returned.
RELATED TAGS
CONTRIBUTOR
View all Courses