Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
keyword
communitycreator

How to check if a string is a keyword in Python

Programming Bytes

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 a keyword that is used to create a class in 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 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))

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, 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

python
keyword
communitycreator
RELATED COURSES

View all Courses

Keep Exploring