How to check if a string is a valid keyword in Python?
What is keyword?
A keyword is a “reserved word” by the language which convey a special meaning to the interpreter. It may be a command or a parameter. it is a word that cannot be used as a variable name, function names, or any other identifiers in the program .
what are python keywords?
Python keywords are some words that convey special meaning. Examples of keywords registered by python are as follow:
continue
, import
, while
, def
, in
, with
,
del
, is
, yield
, False
, elif
, lambda
,
None
, else
, nonlocal
, True
, except
, not
,
and
, finally
, or
,as
, for
, pass
, assert
,
from
, raise
, break
, global
, return
,
class
, if
, try.
How do we check if a string is keyword?
in python there is an inbuilt module keyword
which handles certain operations related to keywords. there is a function too iskeyword()
which is used to check if a string is keyword or not. Returns true if a string is keyword, else returns false.
let's try to write a code that tell us if our string is a keyword or not.
Example
# we need to import "keyword" for keyword operations
import keyword
# state the list of all string we want to test
str_test = ["in", "while", "loop", "break", "evening",
"elif", "assert", "maxwizard", "lambda", "else", "map"]
for i in range(len(str_test)):
# checking which are keywords
if keyword.iskeyword(str_test[i]):
print(str_test[i] + " is python keyword")
else: # if it is false then write
print(str_test[i] + " is not a python keyword")
OUTPUT:
in is python keyword
while is python keyword
loop is not a python keyword
break is python keyword
evening is not a python keyword
elif is python keyword
assert is python keyword
maxwizard is not a python keyword
lambda is python keyword
else is python keyword
map is not a python keyword
But what if you are working how will you make sure you don't use all this keywords as variable? well it might be a difficult task to remember all while assigning variable names. Hence a function kwlist()
is provided in “keyword” module which prints all the 33 python keywords for you here is how to print it below.
Example2
#Python code on how iskeyword() works
# importing "keyword" for keyword operations
import keyword
# printing all keywords at once using "kwlist()"
print ("The list of keywords is below : ")
print (keyword.kwlist)
Output:
The list of keywords is :
['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']
Notice that kwlist
will return the list of all 33 keywords in python.
Top comments (0)