String concatenation (was: Steve D'Aprano, you're the "master". What's wrong with this concatenation statement?)
Thomas 'PointedEars' Lahn
PointedEars at web.de
Sun May 8 20:44:11 EDT 2016
DFS wrote:
> sSQL = "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"
What is wrong with it in Python is that it is unnecessarily inefficient.
Python has implicit string concatenation if all operands are string
literals:
#-----------------------------------------------------------------------
sSQL = ("line 1\n"
"line 2\n"
"line 3")
#-----------------------------------------------------------------------
Alternatively, you can join a list of strings:
#-----------------------------------------------------------------------
sSQL = "\n".join([
"line 1",
"line 2",
"line 3",
])
#-----------------------------------------------------------------------
Python also has a way that avoids using several string literals:
#-----------------------------------------------------------------------
sSQL = """line 1
line 2
line 3"""
#-----------------------------------------------------------------------
or (to have the text aligned)
#-----------------------------------------------------------------------
sSQL = """\
line 1
line 2
line 3"""
#-----------------------------------------------------------------------
With the “%” string operator (deprecated), str.format(), and str.Template,
you can use other values in string values even without concatenation.
Next time, RTFM first:
<https://docs.python.org/3.5/tutorial/introduction.html#strings> p.
Finally, with SQL you should prefer Prepared Statements and Stored
Procedures, not bare strings, to avoid SQL injection:
<https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet>
And if you want to communicate only with a specific person, I strongly
suggest you send *them* an *e-mail* instead of to the newsgroup/mailing
list.
Also, it would be a good idea if you posted under your real name. Internet
is the thing with cables; Usenet is the thing with people. I for one tend
to avoid communicating with few-letter entities; exceptions to that would
probably include only E.T., M.J., ALF, and K.I.T.T.
--
PointedEars
Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
More information about the Python-list
mailing list