用于检查给定字符串是否为关键字的Python程序
给定一个字符串,编写一个Python程序来检查给定的字符串是否是关键字。
- 关键字是不能用作变量名的保留字。
- Python编程语言中有33个关键字。(在Python 3.6.2版本中)
例子:
Input: str = "geeks"
Output: geeks is not a keyword
Input: str = "for"
Output: for is a keyword
我们总是可以使用关键字模块中的kwlist
方法获取当前Python版本中的关键字列表。
# import keyword library
import keyword
keyword_list = keyword.kwlist
print("No. of keywords present in current version :",
len(keyword_list))
print(keyword_list)
输出:
No. of keywords present in current version : 33
[‘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’]
以下是检查给定字符串是否为关键字的Python代码:
# include keyword library in this program
import keyword
# Function to check whether the given
# string is a keyword or not
def isKeyword(word) :
# kwlist attribute of keyword
# library return list of keywords
# present in current version of
# python language.
keyword_list = keyword.kwlist
# check word in present in
# keyword_list or not.
if word in keyword_list :
return "Yes"
else :
return "No"
# Driver Code
if __name__ == "__main__" :
print(isKeyword("geeks"))
print(isKeyword("for"))
输出:
No
Yes