Python program to check if a given string is Keyword or not
Last Updated :
30 Dec, 2022
Given a string, write a Python program that checks if the given string is keyword or not.
- Keywords are reserved words which cannot be used as variable names.
- There are 33 keywords in Python programming language.(in python 3.6.2 version)
Examples:
Input: str = "geeks"
Output: geeks is not a keyword
Input: str = "for"
Output: for is a keyword
We can always get the list of keywords in the current Python version using kwlist method in keyword module.
Python3
import keyword
keyword_list = keyword.kwlist
print ("No. of keywords present in current version :",
len (keyword_list))
print (keyword_list)
|
Output:
No. of keywords present in current version : 33 [‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
Below is the Python code to check if a given string is Keyword or not:
Python3
import keyword
def isKeyword(word) :
keyword_list = keyword.kwlist
if word in keyword_list :
return "Yes"
else :
return "No"
if __name__ = = "__main__" :
print (isKeyword("geeks"))
print (isKeyword(" for "))
|
Using built-in iskeyword() function:
The keyword module is a built-in module in Python that provides tools for working with keywords. It has a function called iskeyword() which takes a string as an argument and returns True if the string is a keyword in Python, and False if it is not.
In this code, we are using the iskeyword() function to check whether the strings “geeks” and “for” are keywords in Python. The first call to iskeyword() will return False because “geeks” is not a keyword, and the second call will return True because “for” is a keyword.
The time complexity of this code is O(1) because the iskeyword() function is a constant-time operation. The space complexity is also O(1) because we are only storing a single string in memory.
Python3
import keyword
print (keyword.iskeyword( "geeks" ))
print (keyword.iskeyword( "for" ))
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...