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

ตรวจสอบว่า String เป็น Valid Identifier ใน Python หรือไม่

โจทย์: กำหนด String ตรวจสอบว่าเป็น Valid Python Identifier หรือไม่ เกณฑ์:

  1. เริ่มต้นด้วย Underscore '_' หรือ ตัวอักษร (A-Z, a-z)
  2. ไม่มี Whitespace
  3. ตัวอักษรถัดไป: ตัวอักษร, ตัวเลข, Underscore เท่านั้น (ไม่มี Special Char: $, #, % ฯลฯ)

ตัวอย่าง

id = "_hello_56" → True

อัลกอริทึม

  1. ตรวจสอบตัวแรก: isalpha() หรือ '_'
  2. วนตัวที่ 2 ขึ้นไป: isalnum() หรือ '_'
  3. ผ่านทั้งหมด → True

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

def solve(s):
    if not s[0].isalpha() and s[0] != '_':
        return False
    for ch in s[1:]:
        if not ch.isalnum() and ch != '_':
            return False
    return True

id = "_hello_56"
print(solve(id))

Input / Output

Input: "_hello_56"
Output: True
หมายเหตุ: Python มี Built-in str.isidentifier() ทำงานนี้ได้โดยตรง