Python 处理字符串匹配
Python dealing with string-matching
有这样一个字符串:
mystr = 'account_id 37318 not found'
我想知道如何写一个比以下更好的条件:
if 'account_id' not in str and 'not found' not in str:
doSomething()
我想一定是这样的:
if 'account_id' + %any substring% + 'not found' not in str:
doSomething()
可能正则表达式会有所帮助,但我不擅长使用它。
提前致谢。
您可以使用 all
而不要使用内置关键字作为变量名。
if all(i not in s for i in ('not found', 'account_id')):
示例:
>>> 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
>>>
这可能会有所帮助。
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'
如果有帮助请告诉我:)。
有这样一个字符串:
mystr = 'account_id 37318 not found'
我想知道如何写一个比以下更好的条件:
if 'account_id' not in str and 'not found' not in str:
doSomething()
我想一定是这样的:
if 'account_id' + %any substring% + 'not found' not in str:
doSomething()
可能正则表达式会有所帮助,但我不擅长使用它。
提前致谢。
您可以使用 all
而不要使用内置关键字作为变量名。
if all(i not in s for i in ('not found', 'account_id')):
示例:
>>> 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
>>>
这可能会有所帮助。
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'
如果有帮助请告诉我:)。