Spread a statement over various lines
codewizard at gmail.com
codewizard at gmail.com
Wed Sep 18 19:18:00 EDT 2019
More information about the Python-list mailing list
Wed Sep 18 19:18:00 EDT 2019
- Previous message (by thread): Spread a statement over various lines
- Next message (by thread): Spread a statement over various lines
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Wednesday, September 18, 2019 at 9:01:21 AM UTC-4, Manfred Lotz wrote: > On Wed, 18 Sep 2019 08:30:08 +0200 > Peter Otten <__peter__ at web.de> wrote: > > > Manfred Lotz wrote: > > > > > I have a function like follows > > > > > > def regex_from_filepat(fpat): > > > rfpat = fpat.replace('.', '\\.') \ > > > .replace('%', '.') \ > > > .replace('*', '.*') > > > > > > return '^' + rfpat + '$' > > > > > > > > > As I don't want to have the replace() functions in one line my > > > question is if it is ok to spread the statement over various lines > > > as shown above, or if there is a better way? > > > > Sometimes you can avoid method-chaining: > > > > >>> REP = str.maketrans({".": "\\.", "%": ".", "*": ".*"}) > > >>> def regex_from_filepat(fpat): > > ... return fpat.translate(REP) > > ... > > >>> regex_from_filepat("*foo.%") > > '.*foo\\..' > > > > Very interesting. Thanks for this. While I think that str.translate() is the right tool for this job, here's another way to avoid line continuations (not necessarily better): def regex_from_filepat(fpat): replacements = [ ('.', '\\.'), ('%', '.'), ('*', '.*'), ] rfpat = fpat for old, new in replacements: rfpat = rfpat.replace(old, new) return '^' + rfpat + '$'
- Previous message (by thread): Spread a statement over various lines
- Next message (by thread): Spread a statement over various lines
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list