我有一個正則表達式這樣的更換每場比賽:用不同的詞
findthe = re.compile(r" the ")
replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"
我所試圖做的是從列表與相關的替換詞替換每次出現這樣最終判決會是這樣的:
>>> print sentence
This is firstthe first sentence in secondthe whole universe
我試圖用re.sub
內部for循環中列舉了更換,但它看起來像re.sub
回報所有事件。有人能告訴我如何有效地做到這一點?
不幸的是,替換邏輯對我而言稍微複雜一些。我提供的是一個測試用例。就我而言,可能會有10到20個。它仍然可以使用你的方法完成,但我正在尋找更簡潔的方法。但+1爲你的幫助。 – Legend
謝謝 - 檢查最後一個解決方案。 –
簡直太棒了!再次感謝您的時間。 – Legend