Python 使用split(";:";)从字符串中获取数字,但我一直缺少第一个数字
我需要从几个字符串中提取2个数字 这是一个示例和我正在使用的代码: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
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我认为这是一个完全价值中立的问题。