Spread a statement over various lines

Peter Otten __peter__ at web.de
Wed Sep 18 02:30:08 EDT 2019


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\\..'

Generally speaking a long statement may be a hint that there is an 
alternative spelling.





More information about the Python-list mailing list