Exercise changing last element

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 data input and output must be   main program

I did as follows:

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)

Somehow this way I did it right by doing the following test it does not go 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 would like to know how to make the word aa not replaced, but rather the word a so that it looks like this:

a a b b KKK c b d aa
    
asked by anonymous 08.10.2018 / 14:48

3 answers

3

Hello, you can separate the original string into spaces.

Ex.

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

And then just browse the resulting list by comparing the string with the new one that will be changed.

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

This way you can store the positions in a variable (overwriting) and in the end you will have the value of the last position of the occurrence there, just change it.

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

It's worth checking for at least one occurrence.

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

  

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

    
08.10.2018 / 15:20
2

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

Imagine that you have the old word a to replace with KKK the regex would be:

\b(a)\b(?!.*\b\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
  - 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 another word "a" .

View on 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\b)", palavraNova, frase) # aplicar regex
print(novaFrase)

See it working on Ideone

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

  • Regular Expression
  • Replacement
  • The string to be replaced
  • 08.10.2018 / 18:32
    1

    You can use the str.rpartition method that will split the string on the last occurrence of the separator, returning a tuple of 3 values: the part of the string before splitting, the separator itself, and the part after splitting. To replace with the new word, simply merge the two parts with the new one.

    >>> 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 this way would it not replace only the word, but the last occurrence of it in string . The phrase piquenique would turn piqueniQUE , even though it does not have the word replaced que . To do so, it will require some extra validation conditions that I leave to your discretion to elaborate them.

        
    09.10.2018 / 21:10