[英]Python - replace letters in a string only once
我需要弄清楚如何在 python 中只替換一次字母。
例子:
s = "a b c d b"
# change letter 'a' to "bye" and letter 'b' to "hay"
# .replace function is problematic because:
s = s.replace('a', "bye")
print(s)
# will print to "bye b c d b" now if I try to replace letter b
# it will replace the first b of "bye" aswell thats not what I want
# output I want: "bye hay c d hay"
任何幫助表示贊賞
您可以使用re.sub ,如下所示:
import re
s = "a b c d b"
def repl(e, lookup={"a": "bye", "b": "hay"}):
return lookup.get(e.group(), e.group)
result = re.sub("[ab]", repl, s)
print(result)
輸出
bye hay c d hay
引用sub
的文檔:
返回通過替換 repl 替換 string 中最左邊的不重疊模式出現的字符串。 如果未找到模式,則返回字符串不變。 repl 可以是字符串或函數
如果您知道原始字符串中不存在的字符,最簡單的方法(不需要額外的包)是將所有字符替換為那些“臨時”字符,然后替換這些臨時字符。 例如:
s = 'a b c d b'
s = s.replace('a', '\0').replace('b', '\1') # Put temporary characters
s = s.replace('\0', 'bye').replace('\1', 'hay') # Replace temporary characters
我喜歡 Dani Mesejo 的使用re.sub
的建議,但我發現包裝在一個方便的函數中時更容易使用,如下所示:
import re
def multi_replace(text, changes):
return re.sub(
'|'.join(changes),
lambda match: changes[match.group()],
text
)
text = 'a b c d b'
changes = {'a': 'bye', 'b': 'hay'}
text = multi_replace(text, changes)
print(text)
輸出:
bye hay c d hay
您可以簡單地使用任何文本和更改字典作為輸入調用multi_replace()
,即使是動態生成的,它也會很高興地返回更新的文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.