如何检查字符串是否是 Python 中的有效关键字?
programmingpythonserver side programming更新于 2025/3/14 21:32:17
要检查字符串是否是有效关键字,请导入关键字模块并使用 iskeyword() 方法。这样,您可以直接一次显示所有关键字并进行验证。
假设以下是我们的输入 -
else
以下是输出。"else"是 Python 中的关键字 -
关键字
检查字符串是否是 Python 中的有效关键字
示例
import keyword # Create a List myList = ["for", "amit", "val", "while"] # Display the List print("List = ",myList) keyword_list = [] non_keyword_list = [] # Looping and verifying for keywords for item in myList: if keyword.iskeyword(item): keyword_list.append(item) else: non_keyword_list.append(item) print("\nKeywords= " + str(keyword_list)) print("Non-Keywords= " + str(non_keyword_list))
输出
List = ['for', 'amit', 'val', 'while'] Keywords= ['for', 'while'] Non-Keywords= ['amit', 'val']
通过显示所有关键字来检查字符串是否为有效关键字
现在让我们显示所有关键字 −
示例
import keyword # Fetch all the Keywords kwlist = keyword.kwlist # Display the Keywords print("Keywords = ",kwlist)
输出
Keywords = ['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 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

