Home > Mobile >  Replacing characters with some restrictions
Replacing characters with some restrictions

Time:12-24

I have a list of strings in Python and I want to create a function that perform many replacements. Some of them are:

  • Replace "o agrícola" for "trabajo agrícola"
  • Replace "ob agricola" for "trabajo agrícola"

One solution that comes to my mind is:

text = str(text).replace('o agricola','trabajo agrícola')
text = str(text).replace('t agricola','trabajo agrícola')

One of the issues:

text = 'obrero agricola' is transformed into 'obrertrabajo agrícola'

Is there a solution that respects these two conditions?

  • 'obrero agricola' is mapped into 'obrero agrícola'

  • 'o something' is mapped into 'o something' (it fixes 'o' if it's mixed with other words)

CodePudding user response:

Use word boundaries along with re.sub:

text = 'ob agricola and obrero agricola'
text = re.sub(r'\b(?:o agrícola|ob agricola)', 'trabajo agrícola', text)
print(text)  # trabajo agrícola and obrero agricola
  • Related