How to check if a given word is a Python keyword or not?

PythonServer Side ProgrammingProgramming

In this program, we will check whether a given word is a python keyword or not. To do so, we will use the function iskeyword() from the keyword library.

Algorithm

Step 1: Import keyboard.
Step 2: Check if the given string is a keyword or not.

Example Code

Live Demo

import keyword
words = ["city", "music", "in", "if"]
for word in words:
   if keyword.iskeyword(word):
      print("{} is a keyword".format(word))
   else:
      print("{} is not a keyword".format(word))

Output

city is not a keyword
music is not a keyword
in is a keyword
if is a keyword
raja
Published on 17-Mar-2021 07:20:55
Advertisements