Exercise changing last element

Asked

Viewed 316 times

1

exercise:

Write a function that receives a phrase and an old word and a new word. The function should return a string containing the phrase original, but with the last occurrence of the old word replaced by the new word. The input and output of data should be done in the core program

I did it this way:

frase=input('digite uma frase:')
palavraAntiga = input('digite uma palavra da frase:')
palavraNova = input('digite uma palavra nova pra substitui-la:')
restante = frase.rsplit(palavraAntiga, 1)
frase = palavraNova.join(restante)
print(frase)

In a way that I made it work but by doing the following test it does not come out the way I want. Test:

digite uma frase:a a b b a c b d aa
digite uma palavra da frase:a
digite uma palavra nova pra substitui-la:KKK
a a b b a c b d aKKK

I wonder how do I make that word aa not replaced but only the word to to keep it that way:

a a b b KKK c b d aa

3 answers

3


Hello, can you separate the string original in the spaces.

Ex.

alphabet = "a b c d e f g ee"
old = "e"
new = "kk"
last = -1;
data = alphabet.split()

And then just go through the resulting list by comparing the string with the new that will be exchanged.

for index, temp in enumerate(data):
    if temp == old:
        last = index

This way you can go storing the positions in a variable (overwriting) and at the end you will have the value of the last position of the occurrence there is only exchange.

if last != -1:
    data[last] = new

It is interesting to check if there is at least one occurrence.

Then just unite again with alphabet = " ".join(data) and display print alphabet.

NOTE: Note the python version you are using and make the corrections for it

2

Just to complement and see other solutions to the problem, also manages to solve through a regular expression not very elaborate.

Imagining you have the old word a to be replaced by KKK the regex would be:

\b(a)\b(?!.*\b\1\b)

Explanation:

\b  - Inicio de palavra
(a) - Captura da palavra "a"
\b  - Fim de palavra
(?! - Negative lookahead - Que não tenha à frente
.*  - Qualquer coisa
\b  - Seguida de inicio de palavra
\1  - Com a mesma captura feita antes
\b  - E fim de palavra

Reading in Portuguese would be something like: Capture the word "a" that does not have in front another word "a".

See in regex101

In Python code:

import re
frase=input('digite uma frase:')
palavraAntiga = input('digite uma palavra da frase:')
palavraNova = input('digite uma palavra nova pra substitui-la:')
novaFrase = re.sub(r"\b(" + palavraAntiga + r")\b(?!.*\b\1\b)", palavraNova, frase) # aplicar regex
print(novaFrase)

Watch it work on Ideone

The regex application was done with the re.sub which receives the following parameters:

  1. Regular expression
  2. The substitution
  3. The string to replace

1

You can use the method str.rpartition that will divide the string in the last occurrence of the separator, returning a tuple of 3 values: the part of the string before the division, the separator itself and the part after the division. To replace by the new word, just join the two parts with the new.

>>> frase = "da forma que fiz funciona, que coisa, não?"
>>> before, separator, after = frase.rpartition('que')
>>> nova_frase = f'{before}QUE{after}'
>>> print(nova_frase)
da forma que fiz funciona, QUE coisa, não?

But only in this way would it replace not only the word, but the last occurrence of it in the string. The phrase piquenique viraria piqueniQUE, even if the word is not replaced que. For this, it will require some extra conditions of validation that I leave to your discretion to elaborate them.

Browser other questions tagged

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