user3078335
user3078335

Reputation: 781

Print actual string found

I have this code which checks if a word from the list "Markers" can be found in the string "Translation".

Translation= words.split("Translation:",1)[1]
if any(x in Translation for x in Markers):
    print "found"

How do i print the actual string that is found. I tried doing this

Translation= words.split("Translation:",1)[1]
if any(x in Translation for x in Markers):
    print x

But i kept getting an error. New to Python. Any help will be greatly appreciated.

Upvotes: 1

Views: 95

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

You cannot get that with any function, as it returns a boolean. So you need to use a for loop like this

for item in markers:
    if item in translation:
        print item
        break
else:
    print "Not Found"

If you want to get all the matching elements then you can use a list comprehension, like this

print [item for item in markers if item in translation]

As Martijn suggested in the comments, we can simply get the first match with

print next((x for x in markers if x in translation), None)

If there is no match, then it will return None.

Note that, PEP-8 suggests us to not to name our local variables with initial capital letters. So, I named with lowercase letters.

Upvotes: 3

Related Questions