list to string

Brian Quinlan BrianQ at ActiveState.com
Tue Feb 27 20:14:49 EST 2001


Calm down Tim, my last example was not meant as a HOWTO for joining strings,
it was demonstrate how Glen's loop could be simplified by:

1) Iterating accross the list elements directly instead of my index
2) Avoiding the unnecessary use of join (since, in his example, his is
joining a string of length 1 on each iteration).

-----Original Message-----
From: python-list-admin at python.org
[mailto:python-list-admin at python.org]On Behalf Of Delaney, Timothy
Sent: Tuesday, February 27, 2001 4:43 PM
To: python-list at python.org
Subject: RE: list to string


> import string
>
> mylist = ['d','o','g']
> mystring = string.join( mylist, '' )
> print mystring
>
> OR (and I hate this style):
>
> mylist = ['d','o','g']
> mystring = ''.join( mylist )
> print mystring
>
> OR (if you want to do the loop yourself):
>
> mylist = ['d','o','g']
> mystring = ''
> for j in mylist:
>     mystring = mystring + j
> print mystring

I have no idea why anyone would suggest doing the loop yourself. The first
one is good, the second is functionally just as good (although horrible).

However, the third method has a number of really horrible drawbacks.

We assume that the join() method is optimised. It will probably be written
in C (for CPython), and designed to use as little time and space as
possible.

OTOH, doing the loop oneself means that you create a new string *every* time
you go through the loop. As the string gets larger, more and more space
needs to be allocated, and more data needs to be copied *every* time through
the loop.

There is a standard idiom in python for joining the (string) elements of a
sequence into a string - string.join(). This is most likely to be the
fastest, most efficient and most understandable way to do it.

The important thing is to know the core libraries supplied with python very
well, and to always try to find pre-done things in the optional libraries
before writing it yourself.

Code re-use is good.

''.join() is evil ;)

*Never* have a loop like (for example):

	text = ''

	for line in f.xreadlines()
		text += line

instead do

	text = []

	for line in f.xreadlines()
		text.append(line)

	text = string.join(text, '\n')

It will be much faster and use much less memory. Of course, for this
particular case, there is a much better method ...

	text = string.join(f.readlines(), '\n')

or even

	text = f.read()	# may have slightly different semantics to the above
depending on platform, file and open mode

but I will ignore those as I was trying to demonstrate a different idiom :)

Tim Delaney
Avaya Australia

--
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list