1

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?

1
  • the condition should be if "mystring" in item Commented Oct 29, 2011 at 0:24

3 Answers 3

5

You want it to be:

if "mystring" in item:
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

4

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.