![](/img/trans.png)
[英]How to split a string on a character that occurs more than once inside the string
[英]Replace a pattern in a string once which occurs more than once
我有一個字符串:
I am Tony not charlie, Hey charlie how's you?
我想取代第二個“查理”,但不是第一個。
預期字符串:
I am Tony not charlie, Hey Tony how's you?
我正在使用以下聲明來執行此操作
>>> re.sub(r',\s\w{3}\scharlie\s', ' Tony ', 'I am Tony not charlie, Hey charlie how\'s you\?')
"I am Tony not charlie Tony how's you?"
但它取代了我想要的東西。
我怎樣才能讓它只替換第二個“查理”而沒有別的?
用自己替換第一個子字符串(及其后面的所有子字符串)並添加limit = 1以防止替換第4個,第6個等事件。
s = "I am Tony not charlie, Hey charlie how's you?"
print re.sub('(charlie.*?)charlie', r'\1Tony', s, 1)
您需要在表達式中使用分組。
看看這是不是你想要的:
>>> re.sub(r'(,\s\w*\s)charlie', r'\1Tony', r"I am Tony not charlie, Hey charlie
how's you?")
"I am Tony not charlie, Hey Tony how's you?"
對於固定模式(不是你的情況),后視/前方斷言可能很方便:
re.sub(r'(?<=Hey )charlie','Tony',string
)
您可以創建自己的替換功能。 您在要替換的單詞上拆分輸入句子,並檢查要替換發生的單詞的索引:
def rreplace(s, delimiter, replacement, positions=[1]):
result = []
sentences = s.split(delimiter)
for i, sentence in enumerate(sentences):
result.append(sentence)
if not i == len(sentences)-1:
if i in positions:
result.append(replacement)
else:
result.append(delimiter)
return "".join(result)
此功能允許您選擇要替換的事件。 要替換的默認索引是“1”,即第二次出現:
s = "I am Tony not charlie, Hey charlie how's you?"
delimiter = "charlie"
replacement = "Tony"
print rreplace(s, delimiter, replacement)
# I am Tony not charlie, Hey Tony how's you?
您還可以通過覆蓋位置參數來選擇多個替換:
s = "charlie charlie charlie"
delimiter = "charlie"
replacement = "Tony"
print rreplace(s, delimiter, replacement, [0, 2])
# Tony charlie Tony
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.