Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an item from list matching a substring

How do I remove an element from a list if it matches a substring?

I have tried removing an element from a list using the pop() and enumerate method but seems like I'm missing a few contiguous items that needs to be removed:

sents = ['@$\tthis sentences needs to be removed', 'this doesnt',      '@$\tthis sentences also needs to be removed',      '@$\tthis sentences must be removed', 'this shouldnt',      '# this needs to be removed', 'this isnt',      '# this must', 'this musnt']  for i, j in enumerate(sents):   if j[0:3] == "@$\t":     sents.pop(i)     continue   if j[0] == "#":     sents.pop(i)  for i in sents:   print i 

Output:

this doesnt @$  this sentences must be removed this shouldnt this isnt #this should this musnt 

Desired output:

this doesnt this shouldnt this isnt this musnt 
like image 726
alvas Avatar asked Oct 01 '12 02:10

alvas


People also ask

How do I remove the matching string from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do I remove a specific item from a list?

Use del to remove an element by index, pop() to remove it by index if you need the returned value, and remove() to delete an element by value. The last requires searching the list, and raises ValueError if no such value occurs in the list.

How do you remove the item at a given index from a list?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.


2 Answers

How about something simple like:

>>> [x for x in sents if not x.startswith('@$\t') and not x.startswith('#')] ['this doesnt', 'this shouldnt', 'this isnt', 'this musnt'] 
like image 63
D.Shawley Avatar answered Sep 30 '22 12:09

D.Shawley


This should work:

[i for i in sents if not ('@$\t' in i or '#' in i)] 

If you want only things that begin with those specified sentential use the str.startswith(stringOfInterest) method

like image 33
mjgpy3 Avatar answered Sep 30 '22 14:09

mjgpy3