在python列表中使用startswith()函数 [英] Using startswith() function inside lists in python
问题描述
我在下面有以下字符串的列表
I had the list with following strings below
some_list = ['9196358485','9966325645','8846853128','8-4-236/2','9-6-32/45','Need to fetch some strings']
从上面的字符串中,我只希望不是以91,9,8
开头的字符串,而是要以8-, 9-
From the above strings i want only strings that does n't start with 91,9,8
but want strings starting with 8-, 9-
下面是我的代码
[i for i in some_list if all(not i.startswith(x) for x in ['91','8','9'])]
结果:
['Need to fetch some strings']
在上面通过使用['91','8','9']
作为条件是删除以9 and 8
开头的字符串,这是正确的,但是我不希望从列表中也删除9-, 8-
,实际上我的意图是以9 and 8
开头的字符串应该像上面那样被忽略,以9- and 8-
开头的字符串也不应该被忽略,我们是否可以在一行中编写两个条件,以采用以8-,9-
开头的字符串并忽略何时以
In the above by using ['91','8','9']
as the condition is deleting the strings starting with 9 and 8
which is correct, but i don't want 9-, 8-
also to be removed from the list, actually my intension is if the strings starting with 9 and 8
should be ignored as above and strings starting with 9- and 8-
should not be ignored , can we write two conditions in a single line with concept of taking strings starting with 8-,9-
and ignoring when strings starts with 9 or 8
in the above code i had written.
任何人都可以让我知道做这件事.............
Can anyone please let me know hoe to do this.............
修改后的代码:
感谢您的支持,如果您不认为这是另一个问题,我有一些实际输出,下面的代码不起作用
Thanks for all of u r support if u don't think this is another question i had some actual output on which the below code is not working
some_list = ['Mr K V Prasad Reddy(MD)',
'+(91)-9849633132, 9959455935',
'+(91)-9849633132',
'Near NRI College,Opp Vijaya Bank,Nizam Pet Road,Nizampet,Hyderabad - 502102',
'9196358485',
'9966325645',
'8846853128',
'8-4-236/2',
'9-6-32/45',
'Need to fetch some strings']
当我使用正则表达式应用bwlow代码时,得到以下输出 结果:
When i apply the bwlow code using regex i got following output result:
['Mr K V Prasad Reddy(MD)',
'+(91)-9849633132, 9959455935',
'+(91)-9849633132',
'Near NRI College,Opp Vijaya Bank,Nizam Pet Road,Nizampet,Hyderabad - 502102',
'8-4-236/2',
'9-6-32/45',
'Need to fetch some strings']
实际上我不希望列表中包含所有电话号码,因此有时会以上述格式使用91
有时8
有时9
Actually i don't want all phone numbers from the list, so they will be in the above format sometimes starting with 91
sometimes 8
sometimes 9
我们如何从列表中删除所有这些电话号码?
How can we remove all those phone numbers from the list?
推荐答案
使用正则表达式:
>>> import re
>>> [i for i in some_list if not re.match(r"[98]\B|+\(91\)", i)]
['8-4-236/2', '9-6-32/45', 'Need to fetch some strings']
\B
仅在字母数字字符串中匹配,因此它在9
和1
之间匹配,而在9
和-
之间不匹配.
\B
matches only within alphanumeric strings, so it matches between 9
and 1
but not between 9
and -
.
这篇关于在python列表中使用startswith()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!