Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace within multiline string

Tags:

python

string

One of my modules (t_mesg.py) has a multi-line string:

tm = """
this
is currently
a
test
message
"""

I import this in another module where I would need to replace certain parts of the string with others. However, on the import, the newline chars come in as well and so tm.replace(...) would not work.

>>> from t_mesg import tm
>>> tm
'\nthis\nis \na\ntest\nmessage\n'

If I need to process this imported string to change "is" to "is not" how would I go about it, so that the string looks like this?

tm = """
this
is not currently
a
test
message
"""

TL;DR - how can I perform the replacement ignoring the newline chars?

like image 461
Craig Avatar asked Dec 23 '22 04:12

Craig


1 Answers

Basically you want to perform a word replacement in a string. You can do it using regular expressions & word boundaries, and the hell with newlines or not:

import re

s = "this\n is \n a good \n question"
s = re.sub(r"\bis\b","is not",s)
print(s)

result:

this
 is not 
 a good 
 question

You can revert back with this (which allows some more newlines to be present between both words and preserves them)

s = re.sub(r"\bis\b(\s+)\bnot\b",r"is\1",s)
print(s)

prints:

this
 is 
 a good 
 question

to go a little further, you could introduce punctuation and other non-alpha stuff and using \W you could still manage:

s = "this\n is - not - \n a good \n question"
s = re.sub(r"\bis(\W+)not\b",r"is\1",s)
print(s)

prints ("not" has gone away but not the dash before it):

this
 is -  - 
 a good 
 question
like image 63
Jean-François Fabre Avatar answered Feb 06 '23 00:02

Jean-François Fabre