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

ตรวจสอบสตริงว่าเป็นตัวเลขได้หรือไม่ใน Python

กำหนดสตริง ต้องตรวจสอบว่าแทนตัวเลขได้หรือไม่ เช่น "0.2" → True, "abc" → False, "-2.5" → True, "10" → True

วิธีการ

ใช้การ parse สตริงของภาษา: ลองแปลงเป็น float ถ้าไม่ error → เป็นตัวเลข มิฉะนั้นไม่ใช่

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

class Solution(object):
    def isNumber(self, s):
        s = s.strip()
        try:
            s = float(s)
            return True
        except:
            return False

ob = Solution()
print(ob.isNumber("0.2"))
print(ob.isNumber("abc"))
print(ob.isNumber("Hello"))
print(ob.isNumber("-2.5"))
print(ob.isNumber("10"))

อินพุต

"0.2" "abc" "Hello" "-2.5" "10"

เอาต์พุต

True False False True True