如何檢查一個字串是否是Python中的有效關鍵字?


若要檢查一個字串是否是有效的關鍵字,請匯入關鍵字模組並使用iskeyword()方法。透過此方法,您可以直接顯示所有關鍵字並進行驗證。

假設我們的輸入如下 −

else

以下為輸出。在Python中,“else”是一個關鍵字 −

Keyword

在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']

更新於: 11-08-2022

2K+ 瀏覽量

開啟你的 事業

完成課程獲取認證

開始
廣告
© . All rights reserved.