-1

I would like to make a condition with two possibilities in the same string:

for k in string:
    if 'www.housemike.com/b' in k:
        do something

and

for k in string:
    if 'www.housemike.com/c' in k:
        do something

Is it possible to make this more simplified than:

for k in string:
    if 'www.housemike.com/b' or 'www.housemike.com/c' in k:
        do something

Maybe would it be possible with a regular expression between "b" and "c"?

martineau
  • 119,623
  • 25
  • 170
  • 301
Miguel Barrios
  • 453
  • 7
  • 17
  • maybe you could shorten this line to make it look cool but it would be harder to-understand, I'd suggest you stick to this `if or` for simplicity – gsb22 Oct 28 '20 at 08:45
  • 2
    Is `k` a string or a list? – khelwood Oct 28 '20 at 08:48
  • I have modified the code to make it clearer Thanks everyone for your help – Miguel Barrios Oct 28 '20 at 08:51
  • 1
    I hope you're aware that your current merged condition doesn't do what you think it does. It should be `'www.housemike.com/b' in k or 'www.housemike.com/c' in k:` – Tomerikoo Oct 28 '20 at 08:52
  • OR [Can Python test the membership of multiple values in a list?](https://stackoverflow.com/questions/6159313/can-python-test-the-membership-of-multiple-values-in-a-list) , whatever `k` is... – Tomerikoo Oct 28 '20 at 09:04

2 Answers2

4

Use any() with a list:

if any('www.housemike.com/'+x in k for x in ['b','c']):
  # do something
Wasif
  • 14,755
  • 3
  • 14
  • 34
4

You could use a regex approach with re.search:

for item in k:
    if re.search(r'^www\.housemike\.com/[bc]$', item):
        do something

I am assuming that you want to match entire strings which are these URLs. If not, and you can tolerate substring matches, then just remove the ^ and $ anchors from the regex and use:

www\.housemike\.com/[bc]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • @khelwood I was assuming that the OP were looking for exact matches of the URL in a list of strings, and did not want a substring match. Maybe I'm wrong. – Tim Biegeleisen Oct 28 '20 at 08:46