I can't understand re.sub

Erik python at lucidity.plus.com
Sun Nov 29 16:53:51 EST 2015


On 29/11/15 21:36, Mr Zaug wrote:
> I need to use re.sub to replace strings in a text file.

Do you? Is there any other way?

> result = re.sub(pattern, repl, string, count=0, flags=0);
>
> I think I understand that pattern is the regex I'm searching for and
> repl is the thing I want to substitute for whatever pattern finds but
> what is string?

Where do you think the function gets the string you want to transform from?

> This should be simple, right?

It is. And it could be even simpler if you don't bother with regexes at 
all (if your input is as fixed as you say it is):

 >>> foo = "foo bar baz spam CONTENT_PATH bar spam"
 >>> ' Substitute '.join(foo.split(' CONTENT_PATH ', 1))
'foo bar baz spam Substitute bar spam'
 >>>

E.



More information about the Python-list mailing list