[Tutor] Pythonic way of concatenation of elements in an array
Alan Gauld
alan.gauld at btinternet.com
Fri Jan 27 10:04:13 CET 2012
On 27/01/12 06:44, Andre' Walker-Loud wrote:
> ... I have only had one programming class, and that was 15 years ago or so,
> ...so these are not issues I am aware of.
> I often find myself joining strings (and have mostly used + to do it).
String addition is OK in some languages, or at least better than in
Python so it is not a universal rule of programming. In Python the big
problem is that each addition operation creates a new string so Python
spends a lot of time allocating bigger and bigger chunks of memory only
to throw it away again.
>> print('here is a string %s which has many variables %s %s %s I have to sort out' %(s1,s2,s3,s4))
> ...
> Is this method any better at combining strings than the +?
It is quite a bit better because Python can pre-calculate how much
memory is needed and do it once.
However, I wouldn't get too stressed on speed. String formatting has a
lot of other advantages over join() and is fast enough most of the time.
I tend to use formatting more than join() in my own code, but join() is
best if you are building up a string in a loop say. You can append the
substrings to a list and then join the list at the end.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list