In python, how do i extract a sublist from a list of strings by matching a string pattern in the original list

P Moran picture P Moran · Apr 30, 2013 · Viewed 10.1k times · Source

How do i return a sublist of a list of strings by using a match pattern. For example I have

myDict=['a', 'b', 'c', 'on_c_clicked', 'on_s_clicked', 's', 't', 'u', 'x', 'y']

and I want to return:

myOnDict=['on_c_clicked', 'on_s_clicked']

I think list comprehensions will work but I'm puzzled about the exact syntax for this.

Answer

mgilson picture mgilson · Apr 30, 2013
import re
myOnDict = [x for x in myDict if re.match(r'on_\w_clicked',x)]

should do it...


Of course, for this simple example, you don't even need regex:

myOnDict = [x for x in myDict if x.startswith('on')]

or:

myOnDict = [x for x in myDict if x.endswith('clicked')]

or even:

myOnDict = [x for x in myDict if len(x) > 1]

Finally, as a bit of unsolicited advice, you'll probably want to reconsider your variable names. PEP8 naming conventions aside, these are list objects, not dict objects.