Steve D'Aprano, you're the "master". What's wrong with this concatenation statement?
Tim Chase
python.list at tim.thechases.com
Sun May 8 19:37:38 EDT 2016
While I'm not Steven...
On 2016-05-08 19:10, DFS wrote:
> sSQL = "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"
If you're only doing it once, it's adequate.
If you're doing it within a loop
for thing in some_iter():
s = "line1\n"
s += "line2\n"
s += "line3"
use(s, thing)
it's suboptimal. Solutions include hoisting it out of the loop:
s = "line1\n"
s += "line2\n"
s += "line3"
for thing in some_iter():
use(s, thing)
and just specifying it with a multi-line string (still better off
hoisted out of the loop):
s = """line1
line2
line3"""
for thing in some_iter():
use(s, thing)
If you're accruing in a loop
s = ""
for thing in some_iter():
s += mung(thing)
then that's a bad code-smell (you get quadratic behavior as the
strings are constantly resized), usually better replaced with
s = "".join(mung(thing) for thing in some_iter())
or build them up as a list, then join the results:
lst = []
for thing in some_iter():
if should_use(thing):
lst.append(thing)
s = "\n".join(lst)
-tkc
More information about the Python-list
mailing list