user1006198
user1006198

Reputation: 5397

Python: find out if an element in a list has a specific string

I am looking for a specific string in a list; this string is part of a longer string.

Basically i loop trough a text file and add each string in a different element of a list. Now my objective is to scan the whole list to find out if any of the elements string contain a specific string.

example of the source file:

asfasdasdasd
asdasdasdasdasd mystring asdasdasdasd
asdasdasdasdasdasdadasdasdasdas

Now imagine that each of the 3 string is in an element of the list; and you want to know if the list has the string "my string" in any of it's elements (i don't need to know where is it, or how many occurrence of the string are in the list). I tried to get it with this, but it seems to not find any occurrence

work_list=["asfasdasdasd", "asdasdasdasd my string asdasdasdasd", "asdadadasdasdasdas"]
has_string=False

for item in work_list:
    if "mystring" in work_list:
        has_string=True
        print "***Has string TRUE*****"

print " \n".join(work_list)

The output will be just the list, and the bool has_string stays False

Am I missing something or am using the in statement in the wrong way?

Upvotes: 1

Views: 14408

Answers (3)

ninjagecko
ninjagecko

Reputation: 91094

Method 1

[s for s in stringList if ("my string" in s)]
#     --> ["blah my string blah", "my string", ...]

This will yield a list of all the strings which contain "my string".

Method 2

If you just want to check if it exists somewhere, you can be faster by doing:

any(("my string" in s) for s in stringList)
#     --> True|False

This has the benefit of terminating the search on the first occurrence of "my string".

Method 3

You will want to put this in a function, preferably a lazy generator:

def search(stringList, query):
    for s in stringList:
        if query in s:
            yield s

list( search(["an apple", "a banana", "a cat"], "a ") )
#     --> ["a banana", "a cat"]

Upvotes: 4

Amber
Amber

Reputation: 526583

A concise (and usually faster) way to do this:

if any("my string" in item for item in work_list):
    has_string = True
    print "found mystring"

But really what you've done is implement grep.

Upvotes: 5

TJD
TJD

Reputation: 11896

You want it to be:

if "mystring" in item:

Upvotes: 5

Related Questions