您可以使用正则表达式来获取所有整数值(按它们在数组中的出现顺序)。您可以使用以下代码获取这些值-
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
输出结果
[12, 52, 19, 15]
如果要将所有数字连接为一个数字并将其输出,则可以使用str.isdigit方法对其进行过滤。例如,
>>> s = "12 hello 52 19 some random 15 number" >>> print int(filter(str.isdigit, s)) 12521915