Technology3 min read

Checking whether a String is a Keyword or not in Python

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

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

  1. Import the keyword module.

  2. Initialize the strings which you have to check.

  3. Invoke the method called iskeyword by passing the string to it.

  4. 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.


Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next