Вот полный ответ, показывающий, как это сделать, используя 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')]
Обратите внимание, что это будет соответствовать любой message
, которая содержит подстроку target_word
. Он не будет искать границы слов, например сравните прогон этого с target_word = 'message'
против target_word = 'sag'
- даст те же результаты. Вам может понадобиться регулярное выражение, если ваше сопоставление слов более сложное.