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

วิธี Parse String เป็น Float หรือ Int ใน Python

ใช้ int() และ float() พร้อม try-except จับ ValueError

Parse to Int

try:
    print(int('112'))
except ValueError:
    print('Cannot parse')

ผลลัพธ์

112

Parse to Float

try:
    print(float('112.15'))
except ValueError:
    print('Cannot parse')

ผลลัพธ์

112.15