我有以下字串:
text_one = str("\"A Ukrainian American woman who lives near Boston, Massachusetts, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Russian attacks on Ukraine and the fear these attacks have engendered.")
text_two = str("\n\nMany people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Russian soldiers overtake the area, the Boston-area woman said.\"")
我需要用 $ 替換 s/S 的每個實體,但不是給定單詞中 s/S的第一個實體。所以輸入/輸出看起來像:
> Mississippi
> Mis$i$$ippi
我的想法是做類似'在每個“”字符之后,跳過第一個“s”然后替換所有其他直到“”字符',但我不知道我該怎么做。我還考慮過創建一個串列來處理每個單詞。
uj5u.com熱心網友回復:
解決方案re:
import re
text_one = '"A Ukrainian American woman who lives near Boston, Massachusetts, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Russian attacks on Ukraine and the fear these attacks have engendered.'
text_two = '\n\nMany people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Russian soldiers overtake the area, the Boston-area woman said."'
def replace(s):
return re.sub(
r"(?<=[sS])(\S )",
lambda g: g.group(1).replace("s", "$").replace("S", "$"),
s,
)
print(replace(text_one))
print(replace(text_two))
印刷:
"A Ukrainian American woman who lives near Boston, Mas$achu$ett$, told Fox News Digital on Monday that she can no longer speak on the phone with her own mother, who lives in southern Ukraine, because of the Rus$ian attacks on Ukraine and the fear these attacks have engendered.
Many people in southern Ukraine — as well as throughout the country — are right now living in fear for their lives as Rus$ian soldier$ overtake the area, the Boston-area woman said."
uj5u.com熱心網友回復:
您要做的第一件事是找到第一個 s 的索引
然后,您需要拆分字串,以便在第一個 s 之后得到字串,并將字串的其余部分分成兩個單獨的變數
接下來,用美元符號替換第二個字串中的所有 s
最后,用一個空字串連接兩個字串
test = "mississippi"
first_index = test.find("s")
tests = [test[:first_index 1], test[first_index 1:]]
tests[1] = tests[1].replace("s", "$")
result = ''.join(tests)
print(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494168.html
下一篇:如何在復雜的字串上添加空格?
