Here's a full answer showing how to do it using replace()
.
strings = ['(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)',
'(static string) name (different static string ) message (last static string)']
results = []
target_word = 'message'
separators = ['(static string)', '(different static string )', '(last static string)']
for s in strings:
for sep in separators:
s = s.replace(sep, '')
name, message = s.split()
if target_word in message:
results.append((name, message))
>>> results
[('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message')]
Note that this will match any message
that contains the substring target_word
. It will not look for word boundaries, e.g. compare a run of this with target_word = 'message'
vs. target_word = 'sag'
- will produce the same results. You may need regular expressions if your word matching is more complicated.