Craig
Craig

Reputation: 1985

Python replace within multiline 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?

Upvotes: 4

Views: 16650

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

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

Upvotes: 10

DereckChamboko
DereckChamboko

Reputation: 287

The replace method doesn’t store the altered value in the same variable. You need to store it in another variable and print it.

tm = tm.replace('\nis \n', '\nis not\n')

Upvotes: 1

user3019423
user3019423

Reputation: 61

you could try splitting up the string, replacing the word and joining the array back together.

tm_array = tm.split("\n")
tm_array[1] = "is not"
new_tm = '\n'.join(tm_array)

Upvotes: 0

Related Questions