Check if a string is a keyword or not in Python

In this article, we are going to learn how to check whether the given string is a keyword or not in Python. For this, we have to first understand what is Keyword.

Keyword:–  Keyword is a reserved word in the programming languages, which have their own special meaning. while executing, it conveys their special meaning to the interpreter. And while taking variable in the code, we never take the keyword as a variable name.

As, keywords are present in every language, so there are also so many keywords present in the python language which is listed below:-

True, False, finally, not, or, and, if, else, elif, None, lambda, nonlocal, not, except, as, pass, try, def, in, with, while, import, continue, from, raise, return, global, class, break, from, assert, for, in, with, is, yield, del, etc.

How to check a string is a keyword or not using kwlist

For this we have to import a built-in python module “keyword”, and in the keyword module, there is a method “kwlist” to store all the keyword present in the python language in a list. And if the given string is present in the list then the string is considered as keyword else the string is not the keyword.

import keyword
keyword_list = keyword.kwlist
s = "while"
s1 = "Sachin"
if s in keyword_list:
    print(s,"is a keyword")
else:print(s,"is not a keyword")
if s1 in keyword_list:
    print(s1,"is a keyword")
else:print(s1,"is not a keyword")


while is a keyword

Sachin is not a keyword

Here, in this code, we took so many examples of string to check whether the given string is a keyword or not. For example, we took a string “Sachin”, as we know that this is not a keyword and the output is the same as we expected and for string “while”, it gives the output as while is a keyword.

Checking of string whether it is a keyword or not from list

import keyword
keyword_list = keyword.kwlist
string_list = ["Codespeedy","for","Sachin","If","not","assert","Door"]
for i in string_list:
    if(i in keyword_list):
        print(i,"is a keyword")
    else:print(i,"is not a keyword")


Codespeedy is not a keyword

for is a keyword

Sachin is not a keyword

If is not a keyword

not is a keyword

assert is a keyword

Door is not a keyword

Here, in an example we took the string as “If”, and the output is that this string is not a keyword but we already mentioned that “if” is a keyword, this is because we use the uppercase instead of lowercase for the letter i.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *