Shiva Krishna Bavandla
Shiva Krishna Bavandla

Reputation: 26668

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

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?

Upvotes: 4

Views: 2456

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336178

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

Upvotes: 6

Related Questions