Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Erik Newsgroups: comp.lang.python Subject: Re: I can't understand re.sub Date: Sun, 29 Nov 2015 21:53:51 +0000 Lines: 24 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de jPmiYPqeUgOayLGH8JBJbAlAtkno+xlBKlOq+7yHkZvA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.007 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'repl': 0.09; '1))': 0.16; '21:36,': 0.16; 'from:addr:python': 0.16; 'received:84.93': 0.16; 'received:84.93.230': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'spam"': 0.16; 'substitute': 0.16; 'wrote:': 0.16; 'string': 0.17; 'string,': 0.18; 'transform': 0.18; 'input': 0.18; '>>>': 0.20; 'to:2**1': 0.21; 'simpler': 0.22; 'file.': 0.22; 'header:In-Reply-To:1': 0.24; 'header:User- Agent:1': 0.26; 'function': 0.28; "skip:' 10": 0.28; 'finds': 0.29; 'way?': 0.29; "i'm": 0.30; 'you?': 0.30; 'fixed': 0.31; 'received:84': 0.32; 'foo': 0.33; 'right?': 0.33; 'gets': 0.35; 'could': 0.35; 'text': 0.35; 'replace': 0.35; 'but': 0.36; 'should': 0.36; 'there': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'say': 0.37; 'whatever': 0.39; 'received:192': 0.39; 'to:addr:python.org': 0.40; 'where': 0.40; 'your': 0.60; 'charset:windows-1252': 0.62; 'is.': 0.63 X-CM-Score: 0.00 X-CNFS-Analysis: v=2.1 cv=JN/GyJ+b c=1 sm=1 tr=0 a=Ypmeq7T0cKALDUsRPCToMg==:117 a=Ypmeq7T0cKALDUsRPCToMg==:17 a=0Bzu9jTXAAAA:8 a=EBOSESyhAAAA:8 a=N659UExz7-8A:10 a=JdF7bIIffsysN8642XEA:9 a=pILNOxqGKmIA:10 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.3.0 In-Reply-To: X-Mailman-Approved-At: Mon, 30 Nov 2015 03:35:18 -0500 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:99728 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.