From: Kyle Roberts Date: Thu, 14 Jun 2012 01:34:08 +0000 (-0400) Subject: Add code example to demonstrate proper string concatenation. X-Git-Url: https://git.eng.unimelb.edu.au/public?p=python-guide.git;a=commitdiff_plain;h=62e59a57e48ca6a52c6ad649731a0cf324551e5b Add code example to demonstrate proper string concatenation. The text does a good job of explaining which route to take when concatenating strings, but the mention of "join" might mean nothing to beginners without a concrete example. --- diff --git a/docs/writing/structure.rst b/docs/writing/structure.rst index 0fd4ca5..eecf700 100644 --- a/docs/writing/structure.rst +++ b/docs/writing/structure.rst @@ -391,6 +391,26 @@ its parts, it is much more efficient to accumulate the parts in a list, which is mutable, and then glue ('join') the parts together when the full string is needed. +**Bad** + +.. code-block:: python + + # create a concatenated string from 0 to 19 (e.g. "012..1819") + nums = "" + for n in range(20): + nums += str(n) # slow and inefficient + print nums + +**Good** + +.. code-block:: python + + # create a concatenated string from 0 to 19 (e.g. "012..1819") + nums = [] + for n in range(20): + nums.append(str(n)) + print "".join(nums) # much more efficient + Vendorizing Dependencies ------------------------