Python – Check if given String is Keyword

Check if String is Python Keyword

There are many keywords in Python programming. And there could be requirement to check if a string or word is a Python keyword.

To check if given string is a keyword, pass the string to the function keyword.iskeyword(string) of keyword library.

Examples

1. Check if given string is a keyword

In the following example, we will read a string from the user and then check if the string is a keyword using keyword library.

Python Program

import keyword

if __name__ == '__main__':
	#read string from user
	s = input("Enter a string: ")
	#check if the string is a keyword
	iskey = keyword.iskeyword(s)
	print('Is',s,'a keyword:',iskey)
Copy

Output

C:\python>python example.py
Enter a string: pop
Is pop a keyword: False

C:\python>python example.py
Enter a string: print
Is print a keyword: False

C:\python>python example.py
Enter a string: for
Is for a keyword: True

C:\python>python example.py
Enter a string: import
Is import a keyword: True

Summary

In this tutorial of Python Examples, we learned how to check if a given string or word is a Python keyword.

Code copied to clipboard successfully 👍