How to check if a string is a valid keyword in Python?

PythonProgrammingServer Side Programming

Like other languages, Python also has some reserved words. These words hold some special meaning. Sometimes it may be a command, or a parameter etc. We cannot use keywords as variable names.

In this section we will see how to check a string is valid keyword or not.

To check this things, we have to import the keyword module in Python.

import keyword

In the keyword module, there is a function iskeyword(). It can be used to check whether a string is valid keyword or not.

In the following example, we are providing a list of words, and check whether the words are keywords or not. We are just separating the keywords and non-keywords using this program.

Example code

Live Demo

import keyword
str_list = ['for', 'TP', 'python', 'del', 'Mango', 'assert', 'yield','if','Lion', 'as','Snake', 'box', 'return', 'try', 'loop', 'eye', 'global', 'while', 'update', 'is']
keyword_list = []
non_keyword_list = []
for item in str_list:
   if keyword.iskeyword(item):
      keyword_list.append(item)
   else:
      non_keyword_list.append(item)
print("Keywords: " + str(keyword_list))
print("\nNon Keywords: " + str(non_keyword_list))

Output

Keywords: ['for']

Non Keywords: ['TP']
Keywords: ['for']

Non Keywords: ['TP', 'python']
Keywords: ['for', 'del']

Non Keywords: ['TP', 'python', 'Mango']
Keywords: ['for', 'del', 'assert', 'yield', 'if']

Non Keywords: ['TP', 'python', 'Mango', 'Lion']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop', 'eye']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try', 'global', 'while']

Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop', 'eye', 'update']

The keyword module has another option to get all of the keywords as a list.

Example code

Live Demo

import keyword
print("All Keywords:")
print(keyword.kwlist)

Output

All Keywords:['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']
raja
Published on 23-Nov-2018 07:05:05
Advertisements