In JavaScript I can do something like:
var template = "{a}{b}-{c}{d}";
var myStuff = template
.replace("{a}", a)
.replace("{b}", b)
.replace("{c}", c)
.replace("{d}", d);
I would like to do something similar in python, but due to the fact that python uses indentation for blocks of code, I can't simply write:
myStuff = template
.replace("{a}", a)
.replace("{b}", b)
.replace("{c}", c)
.replace("{d}", d)
I don't want to have to write this:
myStuff = template.replace("{a}", a).replace("{b}", b).replace("{c}", c).replace("{d}", d)
Or this:
myStuff = template
myStuff = myStuff.replace("{a}", a)
myStuff = myStuff.replace("{b}", b)
myStuff = myStuff.replace("{c}", c)
myStuff = myStuff.replace("{d}", d)
They both look ugly (and I don't like my code ugly!).
Is there a way to break a method call chain into new lines in python, just like I did in JavaScript?
In general your only hope is to use line joining. You can always use explicit line joining
myStuff = template \
.replace("{a}", a) \
.replace("{b}", b) \
.replace("{c}", c) \
.replace("{d}", d)
To use implicit line joining you have to come up with somewhere to put parenthesis (implicit line joining is when you have something within paretheses, brackets or braces - if split over several lines the identation does not take effect). For example
myStuff = (template.replace("{a}", a)
.replace("{b}", b)
.replace("{c}", c)
.replace("{d}", d))
Then of course you can probably find special solutions for specific situations, like using string formatting in your example:
myStuff = template.format(a=a, b=b, c=c, d=d)
but that will not work if you're trying to replace something entirely else (it also doesn't fail if a
, b
, c
or d
happens to be something else than a string).
Other answers would get you how to split a statement into multiple lines, But an easier way to achieve what you are doing would be to use str.format()
-
>>> template = "{a}{b}-{c}{d}"
>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4
>>> template.format(**{'a':a,'b':b,'c':c,'d':d})
'12-34'
>>> template.format(a=a,b=b,c=c,d=d)
'12-34'
The first str.format()
unpacks a dictionary into keyword arguments for the function format()
(similar to what the second one does directly) .
Also, you can split the arguments to a function call in multiple lines without having to use \
, Example -
>>> template.format(a=a,
... b=b,
... c=c,
... d=d)
'12-34'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With