python startswith函数,在python列表中使用startswith()函数

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']

From the above strings i want only strings that does n't start with 91,9,8 but want strings starting with 8-, 9-

so below is my code

[i for i in some_list if all(not i.startswith(x) for x in ['91','8','9'])]

result:

['Need to fetch some strings']

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.............

Edited code:

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']

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']

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?

解决方案

Use a regular expression:

>>> 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 matches only within alphanumeric strings, so it matches between 9 and 1 but not between 9 and -.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值