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



To check if a string is a valid keyword, import the keyword module and use the iskeyword() method. With that, you can directly display all the keywords at once and verify.

Let’s say the following is our input −

else

The following is the output. The “else” is a keyword in Python −

Keyword

Check if a string is a valid keyword in Python

Example

import keyword # Create a List myList = ["for", "amit", "val", "while"] # Display the List print("List = ",myList) keyword_list = [] non_keyword_list = [] # Looping and verifying for keywords for item in myList: if keyword.iskeyword(item): keyword_list.append(item) else: non_keyword_list.append(item) print("\nKeywords= " + str(keyword_list)) print("Non-Keywords= " + str(non_keyword_list))

Output

List =  ['for', 'amit', 'val', 'while']

Keywords= ['for', 'while']
Non-Keywords= ['amit', 'val']

Check if a string is a valid keyword by displaying all the keywords

Let us now display all the keywords −

Example

import keyword # Fetch all the Keywords kwlist = keyword.kwlist # Display the Keywords print("Keywords = ",kwlist)

Output

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']

Advertisements