Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีตรวจสอบว่าสตริงเป็นคีย์เวิร์ดที่ถูกต้องใน Python

เช่นเดียวกับภาษาอื่นๆ Python ก็มีคำสงวน คำเหล่านี้มีความหมายพิเศษ บางครั้งอาจเป็นคำสั่ง หรือพารามิเตอร์ เราไม่สามารถใช้คีย์เวิร์ดเป็นชื่อตัวแปรได้

ในส่วนนี้เราจะดูวิธีตรวจสอบว่าสตริงเป็นคีย์เวิร์ดที่ถูกต้องหรือไม่

เพื่อตรวจสอบสิ่งนี้ ต้อง import โมดูล keyword ใน Python

import keyword

ในโมดูล keyword มีฟังก์ชัน iskeyword() ใช้ตรวจสอบว่าสตริงเป็นคีย์เวิร์ดที่ถูกต้องหรือไม่

ในตัวอย่างต่อไปนี้ เราให้ลิสต์ของคำ และตรวจสอบว่าคำเหล่านั้นเป็นคีย์เวิร์ดหรือไม่ เราแค่แยกคีย์เวิร์ดและ non-keywords ด้วยโปรแกรมนี้

ตัวอย่างโค้ด

import keyword
str_list = ['for', 'TP', 'python', 'del', 'Mango', 'assert', 'yield', 'if', 'Lion', 'as', 'Snake', 'box', 'return', 'try', 'loop', 'eye', 'global', 'while', 'update', 'is']
keyword_list = []
non_keyword_list = []
for item in str_list:
    if keyword.iskeyword(item):
        keyword_list.append(item)
    else:
        non_keyword_list.append(item)
print("Keywords: " + str(keyword_list))
print("\nNon Keywords: " + str(non_keyword_list))

ผลลัพธ์

Keywords: ['for']
Non Keywords: ['TP']
Keywords: ['for']
Non Keywords: ['TP', 'python']
Keywords: ['for', 'del']
Non Keywords: ['TP', 'python', 'Mango']
Keywords: ['for', 'del', 'assert', 'yield', 'if']
Non Keywords: ['TP', 'python', 'Mango', 'Lion']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as']
Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as']
Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try']
Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try']
Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop', 'eye']
Keywords: ['for', 'del', 'assert', 'yield', 'if', 'as', 'return', 'try', 'global', 'while']
Non Keywords: ['TP', 'python', 'Mango', 'Lion', 'Snake', 'box', 'loop', 'eye', 'update']

โมดูล keyword มีอีกตัวเลือกหนึ่งคือดึงคีย์เวิร์ดทั้งหมดเป็นลิสต์

ตัวอย่างโค้ด

import keyword
print("All Keywords:")
print(keyword.kwlist)

ผลลัพธ์

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