Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list lookup with partial match

Tags:

python

For the following list:

test_list = ['one', 'two','threefour']

How would I find out if an item starts with 'three' or ends with 'four' ?

For example, instead of testing membership like this:

two in test_list

I want to test it like this:

startswith('three') in test_list.

How would I accomplish this?

like image 660
David Kehoe Avatar asked May 24 '11 21:05

David Kehoe


People also ask

How do you check for partial match in Python?

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.

How do I check if a string matches in Python?

In python programming we can check whether strings are equal or not using the “==” or by using the “. __eq__” function. Example: s1 = 'String' s2 = 'String' s3 = 'string' # case sensitive equals check if s1 == s2: print('s1 and s2 are equal.

How do you match a string to a list in Python?

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.

What is partially matching?

A partial matching is a collection A of arcs with the requirement that each vertex is contained in at most one arc.


3 Answers

You can use any():

any(s.startswith('three') for s in test_list)
like image 133
sth Avatar answered Nov 18 '22 07:11

sth


You could use one of these:

>>> [e for e in test_list if e.startswith('three') or e.endswith('four')]
['threefour']
>>> any(e for e in test_list if e.startswith('three') or e.endswith('four'))
True
like image 28
samplebias Avatar answered Nov 18 '22 08:11

samplebias


http://www.faqs.org/docs/diveintopython/regression_filter.html should help.

test_list = ['one', 'two','threefour']

def filtah(x):
  return x.startswith('three') or x.endswith('four')

newlist = filter(filtah, test_list)
like image 25
sleeplessnerd Avatar answered Nov 18 '22 07:11

sleeplessnerd