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.
Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.
Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses.
Use the in operator for partial matches, i.e., whether one string contains the other string. x in y returns True if x is contained in y ( x is a substring of y ), and False if it is not. If each character of x is contained in y discretely, False is returned.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With