[英]How to replace one substring in multiple strings in Python?
假設我有多個字符串:
string1 = "ab"
string2 = "db"
string3 = "eb"
如何在所有子字符串中替換相同的子字符串? 假設我需要將“ b”替換為“ c”。 我可以確定要執行以下操作,但是有一種簡潔的單行解決方案嗎?
string1 = string1.replace("b", "c")
string2 = string2.replace("b", "c")
string3 = string3.replace("b", "c")
string1,string2,string3=[string.replace('b','c') for string in [string1,string2,string3]]
試試這個整潔的清單理解單線
編輯:我忘了將變量重新分配回字符串,themewhackamadoodle3000擊敗了我!
確實有一種簡單的方法可以執行此操作,例如使用for循環 :
string1,string2,string3=[string.replace('b','c') for string in [string1,string2,string3]]
循環遍歷數組中的每個字符串,並將b替換為c
您可以使用一個類並在列表理解中創建類方法:
class String:
def __init__(self, s):
self.s = s
def replace(self, old, new):
return self.s.replace(old, new)
string1 = "ab"
string2 = "db"
string3 = "eb"
l = [String(i).replace("b", "c") for i in [string1, string2, string3]]
輸出:
['ac', 'dc', 'ec']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.