How to replace a certain sentence of a Python string? Using re.sub()

Asked

Viewed 272 times

0

I would like to replace every expression that starts with characters: *:.

tentativa = 'Olá td bem? *:palavra_proibida*985 td otimo'
resultado = re.sub('*:', '', tentativa)

Result Obtained:

Olá td bem? palavra_proibida*985 td otimo

Expected result:

Olá td bem? td otimo
  • "sentence" wouldn’t be phrase ? the number is always 985 or may be another ?

1 answer

1


>>> import re
>>> tentativa = 'Olá td bem? *:palavra_proibida*985 td otimo'
>>> resultado = re.sub(r'\*:\S+', '', tentativa)
>>> print(resultado)
Olá td bem?  td otimo

This code uses the \S+ which means "1 or more characters that are not space"; which means that it will replace everything that comes after *: until I find the first space.

Note that I also added a bar before the * to "escape" the special behavior that the * has in regular expressions - with the bar it will be treated only as a normal asterisk to be located.

Browser other questions tagged

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