Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用split(";:";)从字符串中获取数字,但我一直缺少第一个数字_Python_String - Fatal编程技术网

Python 使用split(";:";)从字符串中获取数字,但我一直缺少第一个数字

Python 使用split(";:";)从字符串中获取数字,但我一直缺少第一个数字,python,string,Python,String,我需要从几个字符串中提取2个数字 这是一个示例和我正在使用的代码: data = 'Ant Graph first exam is :2 and the score after the second exam is :10' print ([int (s) for s in data.split(":") if s.isdigit()]) 输出[10] 但如果我删除:并稍微更改代码: data = 'Ant Graph first exam is 2 and the sco

我需要从几个字符串中提取2个数字

这是一个示例和我正在使用的代码:

data = 'Ant Graph first exam is :2 and the score after the second exam is :10'
print ([int (s) for s in data.split(":") if s.isdigit()])
输出[10]

但如果我删除:并稍微更改代码:

data = 'Ant Graph first exam is 2 and the score after the second exam is 10'
print ([int (s) for s in data.split(" ") if s.isdigit()])
输出[2,10]


为什么在第一种情况下我会错过数字2?

第一个代码不起作用的原因是它像这样分割数据:

["Ant Graph first exam is","2 and the score after the second exam is ","10"] 
因此,当您尝试在第二项上测试
isdigit()
时,这无法返回数字,因为“2”位于较大的字符串中。而“10”本身就是


希望事情清楚,我没有错。

你在冒号上分裂。2看起来像是被冒号包围的吗?您是否尝试过打印
数据。拆分(“:”
?)?。。。如果这没有帮助,请尝试打印
数据。拆分(“”
并比较结果。@user2357112supportsMonica我认为不需要如此严厉的回答,同样的回答可以更礼貌一些。@Zanzag我认为这是一个完全价值中立的问题。