2

Is there a better way to write something like this ?

 if 'legal' in href_link or 'disclaimer' in href_link or 'contact' in href_link or 'faq' in href_link or 'terms' in href_link or 'log' in href_link:
        continue

preferably in a single line...Where do I look?

sharang gupta
  • 103
  • 4
  • 12

3 Answers3

4

Use the built-in any:

items = ('legal', 'disclaimer', 'contact', 'faq', 'terms', 'log')
if any(x in href_link for x in items):
    continue

You can use the iterable directly in any to have a true one-liner, but then its more readable this way.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

You could build a regular expression. I'm not sure about efficiency, you'd have to compare with @MosesKoledoye's nice answer.

To match against alternatives you use the pipe |. You'd need something like legal|disclaimer|contact|faq|terms|log as a pattern.

You can build that by joining a string '|' with the values:

>>> values = {'legal', 'disclaimer', 'contact', 'faq', 'terms', 'log'}
>>> pattern = '|'.join(values)
>>> pattern
'terms|log|faq|legal|contact|disclaimer'

Using the re (regular expression) module:

>>> import re
>>> href_link = 'link_to_disclaimer.html'
>>> if re.search(pattern, href_link):
...     print('matches')
matches
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
1

@MosesKoledoye's answer is probably the best one for you: it certainly makes much better code to condense the six uniform tests into one iteration.

But you might instead have been asking "How can I break a long conditional to fit into 79 characters?". In other words, you might have been asking about code formatting rather than how to code. In which case my preferred answer is to format it something like this:

if (a in b or
    c in d or
    e not in f or
    g not in h):
    continue
strubbly
  • 3,347
  • 3
  • 24
  • 36
  • Thank you...@MosesKoledoye's answer is more suited...but if unavoidable, this is a nice way to split to avoid the pylint violation – sharang gupta Apr 25 '17 at 10:58