Newbie Q: efficiency of list -> string conversion
jeff at ccvcorp.com
Tue Nov 20 03:26:39 CET 2001
Erik Johnson wrote:
> I am wondering about the efficiency of converting a list of single
> characters into the corresponding string. Here is a trivial example:
> s = "string"
> l = list(s)
> rv = ""
> for i in xrange(len(l)):
> rv += l[i]
> print rv
> This works, but in general, this seems grossly inefficient for large
Yes, you want to use the string method join()--
s = "string"
l = list(s)
rv = "".join(l)
join() will return a string that's created from all the elements in the list
passed to it, separated by copies of the string that it's called on. In the
example above, it's called on the empty string ( "" ). You could also use
it to create, for example, a string of comma-separated or tab-separated
l = [ 'field1', 'field2', 'field3' ]
More information about the Python-list