python .replace() regex

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r(?is)</html>.+, </html>, article)

In general:

text_after = re.sub(regex_search_term, regex_replacement, text_before)

In order to replace text using regular expression use the re.sub function:

sub(pattern, repl, string[, count, flags])

It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.

Examples

>>> import re
>>> re.sub(ra, b, banana)
bbnbnb

>>> re.sub(r/d+, /{id}, /andre/23/abobora/43435)
/andre/{id}/abobora/{id}

python .replace() regex

You can use the re module for regexes, but regexes are probably overkill for what you want. I might try something like

z.write(article[:article.index(</html>) + 7]

This is much cleaner, and should be much faster than a regex based solution.

Leave a Reply

Your email address will not be published. Required fields are marked *