Cho chuỗi chứa ký tự số và dấu chấm, kiểm tra có biểu diễn một số hợp lệ không (ví dụ: "2.5" → True, "xyz" → False).
Phương pháp
Sử dụng cơ chế xử lý ngoại lệ: thử chuyển chuỗi sang float, nếu không lỗi thì là số.
Ví dụ mã Python
def isNumeric(s):
s = s.strip()
try:
s = float(s)
return True
except:
return False
print(isNumeric("0.2"))
print(isNumeric("xyz"))
print(isNumeric("Hello"))
print(isNumeric("-2.5"))
print(isNumeric("10"))
Đầu vào
"0.2" "abc" "Hello" "-2.5" "10"
Đầu ra
True False False True True