Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare string with all values in list

Tags:

python

I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match:

if paid[j].find(d)>=0:     #BLAH BLAH 

If d were an list, what is the most efficient way to see if the string contained in paid[j] has a match to any value in d?

like image 966
Nathan Avatar asked May 06 '10 19:05

Nathan


People also ask

How do you compare strings in a list?

Use sort() method and == operator to compare lists The sorted list and the == operator are used to compare the list, element by element.

Can I use == to compare strings in python?

Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.

Can we use == for string comparison?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.


1 Answers

If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ... 

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]] 

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None) 

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

like image 165
Alex Martelli Avatar answered Oct 07 '22 19:10

Alex Martelli