简体   繁体   中英

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?

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

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')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM