Doubt with Python's str.replace () method

3

I have the following text:

  

'box 1 is blue, box 10 is green, box 100 is empty'

I want to replace 'box 1' with 'package 2', so I do:

>>> texto = 'caixa 1 é azul, caixa 10 está verde, caixa 100 está vazia'
>>> print(texto.replace('caixa 1', 'pacote 2'))
pacote 2 é azul, pacote 20 está verde, pacote 200 está vazia
>>> 

With this I end up replacing everything containing 'caixa 1' at the beginning. How can I work around this problem?

    
asked by anonymous 30.08.2015 / 19:49

3 answers

4
print(texto.replace('caixa 1 ', 'pacote 2 '))

This resolves if you always have the comma afterwards. You have to have a standard that guarantees that it will have no ambiguity, otherwise there is no way. No matter how the text is composed, it must have something fixed that determines the end of the number in an unambiguous way, it can be comma, space, or anything, as long as it is always present. If you can have several different characters, you need to make a more sophisticated algorithm or use RegEx .

    
30.08.2015 / 19:51
3
  

str.replace (old, new [ max])

     
  • old - substring to be modified
  •   
  • new - the new substring
  •   
  • max - number of times to be replaced
  •   

In your case

print(texto.replace('caixa1','pacote 2', 1))
    
20.08.2017 / 21:13
1

Complementing the bigown response, a solution using regular expression follows.

>>> import re
>>> texto = 'caixa 1 é azul, caixa 10 está verde, caixa 100 está vazia'
>>> re.sub(r'\caixa 1\b', 'pacote 2', texto)
>>> 'pacote é azul, caixa 10 está verde, caixa 100 está vazia'
    
02.09.2015 / 06:18