converting an array of chars to a string

Jonathan Hogg jonathan at onegoodidea.com
Tue Jun 25 07:57:59 EDT 2002


On 21/6/2002 12:02, in article 3D1307AF.3070308 at wedgetail.com, "Derek
Thomson" <derek at wedgetail.com> wrote:

> Gerhard Häring wrote:
>> 
>> 
>> Unless Python 1.5.2 compatibilty is a requirement, just use string
>> methods:
>> 
>>     lst = ['a', 'b', 'c', 'd']
>>     s = ''.join(lst)
> 
> And they say you can't write obfuscated code in Python :)
> 
> I would have expected "join" to be a method on the sequence, if
> anything. As in "s = lst.join('')". In fact, I looked for it, as I
> *knew* I'd seen it used before as a method, I just didn't expect it to
> be in the string class.
> 
> I think I'll just stick with string.join for the time being. As it turns
> out, there's more than one way to do it, even in Python ;)

This one confused me too until I thought about it some more. It follows from
the original location of 'join' in the 'string' module that it be moved to
being a string method.

The 'join' method only operates on a list of strings and always returns a
string. If you look at the list methods, they're all generic with regards to
what types the list contains ('reverse', 'sort', 'append', etc.).

The closest generic list method I could think of would be a 'concat' method
that looks something like:

>>> class list2( list ):
...     def concat( self ):
...         import operator
...         return reduce( operator.add, self )
... 
>>> l = list2( ['hello', 'world'] )
>>> l.concat()
'helloworld'
>>> 

which would work on any list of sequences. [A side effect is that it would
also act as a 'sum' method on lists of numbers.]

Jonathan




More information about the Python-list mailing list