Swap lyrics of a Python phrase

Asked

Viewed 1,354 times

1

I have a problem with my code, the letter is not being replaced.

def troca(quero_trocar, trocar_por, frase):
    for letra in frase:
        if(letra == quero_trocar):
            letra = trocar_por
    return frase

I tried to do it this way but it didn’t work either:

def troca(quero_trocar, trocar_por, frase):
    for letra in frase:
        if(letra == quero_trocar):
            frase[letra] = quero_trocar
    return frase

The mistake was:

TypeError: 'str' object does not support item assignment 
  • You just updated the variable letra and not frase.

  • That’s exactly what I’m wondering how to do

2 answers

4


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)
  • 1

    valeuu, helped a lot! XD

0

try to do the following:

def troca(quero_trocar, trocar_por, frase):
    frase = frase.replace(quero_trocar, trocar_por, len(frase))
    return frase

In this case, 'Len(phrase)' causes the 'replace' function to traverse as many characters as possible in the sentence, so it will always switch all the letters without having to enter a looping.

Ex:

quero_trocar = "a"
trocar_por = "b"
frase = "a aba da janela esta aberta"
frase = frase.replace(quero_trocar, trocar_por, len(frase))

The result will be:

'b bbb db jbnelb estb bbertb'

But easy and practical than generating a looping.

  • Thank you, but also that of error :c

Browser other questions tagged

You are not signed in. Login or sign up in order to post.