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
?
Use sort() method and == operator to compare lists The sorted list and the == operator are used to compare the list, element by element.
Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.
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.
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;-).
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