In this tutorial, we are going to learn how to check whether a string is a keyword or not in Python. It's pretty easy. We can check it in just three lines of code.
We need a module called the keyword module to check whether a string is a keyword or not. It's a built-in module so, you don't have to worry about anything. Just follow the below steps.
Steps to Write the Program
-
Import the keyword module.
-
Initialize the strings which you have to check.
-
Invoke the method called iskeyword
by passing the string to it.
-
The method iskeyword
will return True if the provided string is a keyword else it returns False.
Write the code on your own. If you find it challenging, see the code below.
Here's the code:
# importing the keyword module
import keyword
# initializing the strings
string1 = 'for'
string2 = 'or'
string3 = 'hafeezul kareem'
# checking whether they are keywords or not using the iskeyword method
print(f'{string1} is keyword: {keyword.iskeyword(string1)}')
print(f'{string2} is keyword: {keyword.iskeyword(string2)}')
print(f'{string3} is keyword: {keyword.iskeyword(string3)}')
Output:
for is keyword: True
or is keyword: True
hafeezul kareem is keyword: False
Conclusion
If you have any doubts regarding the tutorial, mention them in the command section.