簡體   English   中英

Python 在多行字符串中替換

[英]Python replace within multiline string

我的一個模塊 (t_mesg.py) 有一個多行字符串:

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

我將它導入到另一個模塊中,我需要將字符串的某些部分替換為其他部分。 但是,在導入時,換行符也會出現,因此tm.replace(...)不起作用。

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

如果我需要處理這個導入的字符串以將“是”更改為“不是”,我將如何處理,使字符串看起來像這樣?

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

TL; DR - 如何在忽略換行符的情況下執行替換?

基本上你想在字符串中執行單詞替換。 您可以使用正則表達式和單詞邊界來做到這一點,以及是否使用換行符:

進口重新

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)

打印(“不”已經消失,但它之前的破折號沒有):

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM