Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lấy giá trị integer từ string Python

Dùng regular expression lấy tất cả integer value theo thứ tự xuất hiện trong array. Code sau lấy những giá trị:

Ví dụ

import re
s = "12 hello 52 19 some random 15 number"
# Extract numbers and cast them to int
list_of_nums = map(int, re.findall('\d+', s))
print list_of_nums

Output

[12, 52, 19, 15]

Muốn concat tất cả số thành 1 số và output, dùng str.isdigit method filter. Ví dụ:

>>> s = "12 hello 52 19 some random 15 number"
>>> print int(filter(str.isdigit, s))
12521915