Skip to content Skip to sidebar Skip to footer

I Need To Compare Two Strings And Remove Characters If They Match From String One, Python

I have two strings so for example: string1 = 'abcdefga' string2 = 'acd' I need to make string one return with 'befga' I can replace it but if string1 has two of the same characters

Solution 1:

You can use the maxreplace parameter of replace to replace only the first occurrence;

string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

string1 = "abcdefga"
string2 = "acd"

for ch in string2:
    string1 = string1.replace(ch, '', 1)

print(string1)
'befga'

Post a Comment for "I Need To Compare Two Strings And Remove Characters If They Match From String One, Python"