Python function to check if a given string is a keyword

0 votes
I'm trying to write a python code to check if a given string is a keyword or not. Is there a function that lists down all keywords? or atleast something that lets me check if a string is a keyword or no. Thanks
Jun 17 in Python by Vaibhav
17 views

1 answer to this question.

0 votes

You can get the list of keywords in the current python version using kwlist method in keyword module. Import the keyword module and try something like this:

#import the keyword module
import keyword
#function to check if the word is a keyword
def isKeyword(word) :
#get keyword list
   keyword_list = keyword.kwlist
#check if they word is a prt of the keyword list
   if word in keyword_list :
      return "Yes"
   else :
      return "No"

print(isKeyword("Machine"))
print(isKeyword("while"))
answered Jun 17 by Drishya

Related Questions In Python

+1 vote
1 answer

How to check if a string is null in python

Try this: if cookie and not cookie.isspace(): # the ...READ MORE

answered Aug 20, 2018 in Python by Priyaj
• 56,160 points
1,613 views
0 votes
1 answer

How to check if a substring is present in a string using Python?

To check if the substring exists in ...READ MORE

answered May 9 in Python by Sharan
31 views
0 votes
1 answer

How to check if a given string matches a particular pattern in Python?

You can use re module of python ...READ MORE

answered Jul 3 in Python by Neel
• 1,610 points
18 views
+1 vote
1 answer

How to check if a string is in a file, using python?

Hi, Try the below given code: with open('myfile.txt') as ...READ MORE

answered Jul 4 in Python by Shabnam
• 800 points
20 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 133 views
+4 votes
6 answers
0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12 in Python by Nymeria
• 3,500 points
39 views
0 votes
1 answer

How do I check if a list is empty in python?

Hey @Vedant, that's pretty simple and straightforward: if ...READ MORE

answered May 27 in Python by Karthik
29 views