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

Python – ตรวจสอบว่า List of Strings เป็นตัวเลขทั้งหมด (All Numeric Strings)

ภาพรวม

ใช้ all() ร่วมกับ str.isdigit() ตรวจสอบว่าทุก element ใน list เป็นสตริงตัวเลขทั้งหมด

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


my_list = ["434", "823", "98", "74", "9870"]
print("The list is:", my_list)

my_result = all(s.isdigit() for s in my_list)

if my_result:
    print("All the elements in the list are numeric")
else:
    print("All the elements in the list are not numeric")

ผลลัพธ์

The list is: ['434', '823', '98', '74', '9870']
All the elements in the list are numeric

คำอธิบาย

  • str.isdigit() -> True ถ้าทุกตัวอักษรเป็น digit (0-9)
  • all() -> True ถ้าทุก element ใน iterable เป็น True
  • Short-circuit: หาเจอ False หนึ่งตัวหยุดทันที

ข้อจำกัดของ isdigit()


"123".isdigit()      # True
"-123".isdigit()     # False (มี minus sign)
"12.3".isdigit()     # False (มี decimal point)
"123".isdigit()    # True (full-width digits นับเป็น digit)
"½".isdigit()        # False (numeric แต่ไม่ใช่ digit)

เวอร์ชันที่รองรับ Negative/Float


def is_numeric(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

my_list = ["434", "-123", "12.5", "abc"]
print(all(is_numeric(s) for s in my_list))  # False (เพราะ abc)