Python str.replace() doubt

Asked

Viewed 27,933 times

7

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 that contains 'caixa 1' at first. How can I get around this problem?

  • Add a comma: texto.replace('caixa 1,', 'pacote 2,')

  • Add a space: texto.replace('caixa 1 ', 'pacote 2 '). You cannot be editing the question every time you receive an answer.

3 answers

8


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

I put in the Github for future reference.

This solves if you always have the comma later. You have to have a pattern that ensures that you will not have ambiguity, otherwise there is no way. No matter how the text is composed, it needs to have something fixed that determines the end of the number unambiguously, it can be comma, space, or anything, as long as it is always present. If you can have several different characters, then you need to make a more sophisticated algorithm or use RegEx.

  • Sorry, I did not know how to pass my doubt correctly so I edited to get better; Unfortunately in the text I am using there are no commas or any other character that I can use as limiter.

5

str.replace(old, new[, max])

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

in your case

print(texto.replace('caixa1','pacote 2', 1))

1

Complementing Maniero’s response, follows a solution using regular expression.

>>> 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'

Browser other questions tagged

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