Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
Written By:
4 minute read
PythonPython Keyword

Checking whether a String is a Keyword or not in Python

Posted in Programming   LAST UPDATED: DECEMBER 16, 2019

In this tutorial, we are going to learn how to check whether a string is a keyword or not in Python. It's pretty easy. We can check it in just three lines of code.

We need a module called the keyword module to check whether a string is a keyword or not. It's a built-in module so, you don't have to worry about anything. Just follow the below steps.

Steps to Write the Program

  1. Import the keyword module.

  2. Initialize the strings which you have to check.

  3. Invoke the method called iskeyword by passing the string to it.

  4. The method iskeyword will return True if the provided string is a keyword else it returns False.

Write the code on your own. If you find it challenging, see the code below.

Here's the code:

# importing the keyword module
import keyword

# initializing the strings
string1 = 'for'
string2 = 'or'
string3 = 'hafeezul kareem'

# checking whether they are keywords or not using the iskeyword method
print(f'{string1} is keyword: {keyword.iskeyword(string1)}')
print(f'{string2} is keyword: {keyword.iskeyword(string2)}')
print(f'{string3} is keyword: {keyword.iskeyword(string3)}')


for is keyword: True
or is keyword: True
hafeezul kareem is keyword: False


If you have any doubts regarding the tutorial, mention them in the command section.