1

There's a string like that:

mystr = 'account_id 37318 not found'

I'm wondering how to write an condition better than:

if 'account_id' not in str and 'not found' not in str:
    doSomething()

I guess there must be something like:

if 'account_id' + %any substring% + 'not found' not in str:
   doSomething()

Probably a regular expression might help, but I'm not good with using it.

Thank you in advance.

2
  • 3
    firstly ... str is a very bad variable name. Commented Aug 17, 2015 at 12:47
  • oh, yeah, sure) it's just an example. I'll edit Commented Aug 17, 2015 at 12:58

2 Answers 2

4

You may use all and don't use builtin keywords as variable names.

if all(i not in s for i in ('not found', 'account_id')):

Example:

>>> tr = 'account_id 37318 not found'
>>> tr1 = '2735723'
>>> all(i not in tr for i in ('not found', 'account_id'))
False
>>> all(i not in tr1 for i in ('not found', 'account_id'))
True
>>>
Sign up to request clarification or add additional context in comments.

Comments

2

This may help.

import re
string = 'account_id 37318 not found'

match = re.search(r'\baccount_id\b.*?\bnot found\b',string)
if match:
    print 'Do something'
else:
    print 'Do nothing'

Let me know if it helps :).

1 Comment

probably better to use \baccount_id\b.*?\bnot found\b (not need to describe the start and the end of the string and starting a pattern with a literal string is always more efficient).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.