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

ตรวจสอบสตริงเป็นตัวเลขที่ถูกต้องใน Python

ภาพรวม

โจทย์ตรวจสอบว่าสตริงแทนตัวเลขที่ถูกต้องหรือไม่ (รองรับทศนิยม, ลบ, วิทยาศาสตร์)

ตัวอย่าง

InputOutput
"0.2"True
"abc"False
"Hello"False
"-2.5"True
"10"True

วิธี Pythonic: Try/Except (EAFP)

def isNumeric(s):
    s = s.strip()
    try:
        float(s)
        return True
    except ValueError:
        return False

print(isNumeric("0.2"))
print(isNumeric("xyz"))
print(isNumeric("Hello"))
print(isNumeric("-2.5"))
print(isNumeric("10"))

ข้อดีของวิธีนี้

  • จัดการทุกรูปแบบที่ float() รองรับ: integer, float, scientific (1e10), negative
  • ไม่ต้องเขียน regex ซับซ้อน
  • Pythonic: "Easier to Ask Forgiveness than Permission"

ข้อจำกัด

  • "inf", "nan" → True (float ยอมรับ)
  • "1.2.3" → False
  • เลขใหญ่มากอาจ overflow (แต่ Python รองรับ arbitrary precision int, float มีขีดจำกัด)

ผลลัพธ์

True
False
False
True
True