The irony

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Tue May 10 18:44:08 EDT 2016


On Tuesday, May 10, 2016 at 11:03:47 AM UTC-7, DFS wrote:
> "There should be one-- and preferably only one --obvious way to do it."
> 
> https://www.python.org/dev/peps/pep-0020/
> 
> 

Each method of string concatenation has different uses.

> -----------------------------------
> sSQL =  "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"

This method is simple, easy to read, and is fine for cases where you're not going to be concatenating more than a couple strings *AT RUN-TIME*.


> -----------------------------------
> sSQL = ("line 1\n"
>          "line 2\n"
>          "line 3")

This performs implicit string concatenation *AT COMPILE TIME*.  It doesn't work if the strings you are putting together are variables.

> -----------------------------------
> sSQL = "\n".join([
>           "line 1",
>           "line 2",
>           "line 3",
>         ])

This joins several strings (at run time) with a string separating them.  Though an empty string, comma, or a new line are the most common strings to use, you can use any string.

> -----------------------------------
> sSQL =  """line 1
> line 2
> line 3"""
> -----------------------------------
> sSQL = """\
> line 1
> line 2
> line 3"""

These two are effectively the same, sure.  I'll give you that.

> -----------------------------------
> sSQL = "line 1\n" \
>         "line 2\n" \
>         "line 3"

This is just implicit string concatenation and no real different than your second option except you used the explicit line continuation character instead of using the implicit line continuation created by using parentheses.

> -----------------------------------
> 
> 
> Which is the "one obvious way" to do it?
> I liked:
> 
> sSQL =  "line 1\n"
> sSQL += "line 2\n"
> sSQL += "line 3"
> 
> 
> but it's frowned upon in PEP8.

It's frowned upon because it is incredibly slow when used a lot.  Every time you do a += on a string, it has to re-allocate memory, whereas other methods either figure it out at compile time or figure out how much memory will be needed and allocate it once.



More information about the Python-list mailing list