我的一个模块(t_mesg.py)有一个多行字符串:
tm = """
this
is currently
a
test
message
"""
我将其导入到另一个模块中,我需要将字符串的某些部分替换为其他部分。但是,在导入时,换行符也会出现,因此
tm.replace(...)
不起作用。
>>> from t_mesg import tm
>>> tm
'\nthis\nis \na\ntest\nmessage\n'
如果我需要处理这个导入的字符串以将“is”更改为“is not”,我该如何处理,使字符串看起来像这样?
tm = """
this
is not currently
a
test
message
"""
TL;DR - 如何执行替换而忽略换行符?
基本上你想在字符串中执行单词替换。你可以使用正则表达式和单词边界来做到这一点,不管是否使用换行符:
import re
s = "this\n is \n a good \n question"
s = re.sub(r"\bis\b","is not",s)
print(s)
结果:
this
is not
a good
question
您可以用这个恢复(这允许两个单词之间出现更多换行符并保留它们)
s = re.sub(r"\bis\b(\s+)\bnot\b",r"is\1",s)
print(s)
打印:
this
is
a good
question
更进一步,您可以引入标点符号和其他非 alpha 内容,并使用
\W
您仍然可以管理:
s = "this\n is - not - \n a good \n question"
s = re.sub(r"\bis(\W+)not\b",r"is\1",s)
print(s)
打印(“not”已经消失,但前面的破折号没有消失):
this
is - -
a good
question
replace 方法不会将更改后的值存储在同一变量中。您需要将其存储在另一个变量中并打印它。
tm = tm.replace('\nis \n', '\nis not\n')
您可以尝试拆分字符串,替换单词并将数组重新连接在一起。
tm_array = tm.split("\n")
tm_array[1] = "is not"
new_tm = '\n'.join(tm_array)