Another alternative would be this:
string1 = "chocolate"
string2 = "oca"
result = ''.join(char for char in string1 if char not in string2)
# 'hlte'
print(result)
I mean, we created a Generator Expression (generating expression, in free translation) - which is also used in list comprehensions - which says that:
For each character in string1
, return the one who is not in string2
.
(char for char in string1 if char not in string2)
And we use the method str.join()
to join the characters chosen, that is, to join the characters that met that condition, into a single string, separating them by ''
, which simply serves to keep the characters very close to each other, as in a normal text.
''.join(...)
That would be the same as:
string1 = 'chocolate'
string2 = 'oca'
result = ''
for char in string1:
if char not in string2:
result += char
And this solution (given at the beginning) works on both Python 2 and Python 3.
The point here is that you will not, in fact, be removing characters from string basis (that is, you will not be modifying to string basis), but will be creating a new, from of string groundwork.
Something tells me it’s been answered before
– Maniero
Has anyone ever asked a similar question?
– Guilherme Santana De Souza
@Guilhermesantanadesouza Already Here Here Here
– Marco Souza
Sorry, but I don’t understand. I will edit the question.
– Guilherme Santana De Souza
your answer this here
– Marco Souza
Thanks @Marconciliosouza
– Guilherme Santana De Souza