Spread a statement over various lines
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Wed Sep 18 03:52:21 EDT 2019
On 17.09.19 20:59, 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?
>
One problem with explicit line continuation using \ is that it is
dependent on the backslash being the last character on the line, i.e.
a single space at the end of the line will result in a SyntaxError.
This is why implicit line continuation relying on opened parentheses,
brackets or curly braces is often preferred, and recommended over
backslash continuation in PEP8
(https://www.python.org/dev/peps/pep-0008/#maximum-line-length).
To use implicit line continuation you could either introduce extra
surrounding parentheses as suggested by others, or you may make use
of the parentheses you have already, like so:
def regex_from_filepat(fpat):
rfpat = fpat.replace(
'.', '\\.'
).replace(
'%', '.'
).replace(
'*', '.*'
)
return '^' + rfpat + '$'
More information about the Python-list
mailing list