Bhavani Kannan
Bhavani Kannan

Reputation: 1279

String.Contains in Python

I have a code like this...

if active == 1: // A flag which is set if a Site is Active
    for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')):
        if link.has_key('href'):
           if 'MY_TEXT' in link['href'].upper(): //Check if the link has the string MY_TEXT in it. If it has print it and break the loop
               print link['href']
               break

Now, I want to improvize this code to check MY_TEXT1, MY_TEXT2 and MY_TEXT3 too. I do not want to write plenty of IF statements. Instead I did something like this

a = ['MY_TEXT1', 'MY_TEXT2', 'MY_TEXT3']

if active == 1: // A flag which is set if a Site is Active
    for link in BeautifulSoup(content, parseOnlyThese=SoupStrainer('a')):
        if link.has_key('href'):
            for x in a:
                if link['href'].__contains__(x):
                    print link['href']
                    break

But this did not work. I mean no Syntax/Compile/Run-time error. No output either. What am I doing wrong?

Upvotes: 0

Views: 530

Answers (2)

Duncan
Duncan

Reputation: 95652

A cleaner way to write this would be to use any():

    if link.has_key('href'):
        href = link['href'].upper()
        if any(x in href for x in a):
            print link['href']

Upvotes: 0

NPE
NPE

Reputation: 500277

You don't tell us the input on which it does not work.

One obvious difference between the first version and the second is the lack of .upper() in the second. Is this what's causing the problem?

It is also unclear why you'd replace in with __contains__, but that should not matter either way.

Upvotes: 1

Related Questions