Reputation: 103
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?
Upvotes: 2
Views: 55
Reputation: 3477
@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
Upvotes: 1
Reputation: 24153
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
Upvotes: 1
Reputation: 78564
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.
Upvotes: 4