Python, string are immutable, so if you try to do this:
s = 'abc'
s[0] = 'x'
The result will be a TypeError
(as in fact happened with his second attempt).
In this case, the way is to create another string with the changed characters. One way to do it is to use replace
:
def troca(quero_trocar, trocar_por, frase):
return frase.replace(quero_trocar, trocar_por)
print(troca('a', 'b', 'abacate')) # bbbcbte
The detail is that replace
can swap any string for another, including different sizes:
print(troca('aba', 'x', 'abacate')) # xcate
If this is an exercise and you "need" to use one loop, can iterate by string characters and build the other string:
def troca(quero_trocar, trocar_por, frase):
nova = []
for c in frase:
if c == quero_trocar:
nova.append(trocar_por)
else:
nova.append(c)
return ''.join(nova)
print(troca('a', 'x', 'abacate')) # xbxcxte
In this case, I will save the characters in a list, and at the end I put everything together in a single string, using join
.
But if you want, you can use the syntax of comprehensilist on, much more succinct and pythonic:
def troca(quero_trocar, trocar_por, frase):
return ''.join(trocar_por if c == quero_trocar else c for c in frase)
You just updated the variable
letra
and notfrase
.– Jorge Mendes
That’s exactly what I’m wondering how to do
– Yasmin Yuriko