开发者

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')):
        i开发者_Python百科f 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?


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.


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']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜