Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing pattern matched line from multiline string in python

Tags:

python

I have a multiline text string, that looks like:

AAAA BBBBBB
BBBB VVVV XXXX

CCCCCCCC XXXX

I'd like to come up with a small function that removes an entire line if it contains a word/phrase , so that for above if I lets say sent in 'VVV' as a paremeter the output would be:

AAAA BBBBBB

CCCCCCCC XXXX

There are many examples on stackoverflow, eg Remove lines that contain certain string, which show how to do this for a file, but I'm not sure how without opening a file.

like image 726
user1592380 Avatar asked Sep 14 '25 08:09

user1592380


1 Answers

you can use re.sub:

>>> import re
>>> my_string
'AAAA BBBBBB\nBBBB VVVV XXXX\n\nCCCCCCCC XXXX'
>>> re.sub(".*VVV.*\n?","",my_string)
'AAAA BBBBBB\n\nCCCCCCCC XXXX'

you can define a function and can do for any substring:

>>> def remove(rem,my_string):
...     return re.sub(".*"+rem+".*\n?","",my_string)
... 
>>> remove("VVV",my_string)
'AAAA BBBBBB\n\nCCCCCCCC XXXX'
>>> remove("XXX",my_string)
'AAAA BBBBBB\n\n'
>>> remove("BBB",my_string)
'\nCCCCCCCC XXXX'
>>> remove("CCCC",my_string)
'AAAA BBBBBB\nBBBB VVVV XXXX\n\n'
like image 106
Hackaholic Avatar answered Sep 16 '25 22:09

Hackaholic