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

วิธีดึงตัวเลขจาก String ใน Python

กรณี positive integers เท่านั้น: split แล้ว filter ด้วย isdigit()

>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]

กรณีทั่วไป (รวมลบ, ทศนิยม): ใช้ regex

>> import re
>>> [float(s) for s in re.findall(r'-?\d+\.?\d*', 'he33.45llo -42 I\'m a 32 string 30')]
[33.45, -42.0, 32.0, 30.0]

Regex -?\d+\.?\d* match ตัวเลขลบ/บวก ทศนิยม/จำนวนเต็ม