How to check if a string is a valid keyword in Python?
In programming, a keyword is a “reserved word” by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet.
What is Keywords in Python
Python also reserves some keywords that convey special meaning. Knowledge of these is a necessary part of learning this language. Below is a list of keywords registered by Python.
False, elif, lambda, None, else, nonlocal, True, except, not, and, finally, or, as, for, pass, assert, from, raise, break, global, return, class, if, try, continue, import, while, def, in, with, del is, yield
Python Program to Check if a String is a Keyword
Python in its language defines an inbuilt module keyword that handles certain operations related to keywords. iskeyword() checks if a string is a keyword or not. Returns true if a string is a keyword, else returns false.
Python3
import keyword
keys = [ "for" , "geeksforgeeks" , "elif" , "elseif" , "nikhil" ,
"assert" , "shambhavi" , "True" , "False" , "akshat" ,
"akash" , "break" , "ashty" , "lambda" , "suman" ,
"try" , "vaishnavi" ]
for i in range ( len (keys)):
if keyword.iskeyword(keys[i]):
print (keys[i] + " is python keyword" )
else :
print (keys[i] + " is not a python keyword" )
|
Output
for is python keyword
geeksforgeeks is not a python keyword
elif is python keyword
elseif is not a python keyword
nikhil is not a python keyword
assert is python keyword
shambhavi is not a python keyw...
Print a list of all keywords
Sometimes, remembering all the keywords can be a difficult task while assigning variable names. Hence, kwlist() function is provided in the keyword module which prints all the 33 python keywords.
Python3
import keyword
print ( "The list of keywords is : " )
print (keyword.kwlist)
|
Output
The list of keywords is :
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda...
Next Articles:
Last Updated :
25 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...