[英]I need to compare two strings and remove characters if they match from string one, python
我有兩個字符串,例如: string1 = "abcdefga"
string2 = "acd"
我需要用"befga"
使字符串返回一個,我可以替換它,但是如果string1
有兩個相同的字符,則可以將兩者都刪除我的string1
不斷返回"befg
”:
for char in string1:
for nike in string2:
if char == nike:
string1 = string1.replace(char,"")
您可以使用replace
的maxreplace
參數僅替換第一個匹配項。
string.replace(s,old,new [,maxreplace])
返回字符串s的副本,其中所有出現的子字符串old都替換為new。 如果給出了可選參數maxreplace,則替換第一個出現的maxreplace。
string1 = "abcdefga"
string2 = "acd"
for ch in string2:
string1 = string1.replace(ch, '', 1)
print(string1)
'befga'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.