Operators as functions

Fredrik Lundh fredrik at pythonware.com
Tue Dec 21 04:19:19 EST 2004


Anders Andersson wrote:

> I want to concatinate (I apologize for bad English, but it is not my native language)

fast det stavas iofs inte konkatinera på svenska heller ;-)

> a list of strings to a string.

> And here is the questions: What to replace "concatinating function" with? Can I in some way give 
> the +-operator as an argument to the reduce function?

see the operator module.

but as other have already pointed out, turning a list of strings into a single
string is usually written as:

    s = "".join(seq)

in contemporary Python, or

    import string
    s = string.join(seq, "")

in pre-unicode python style (note that in the first case, the "join" operation is
actually a method of the separator.  seq can be any object that can produce
a sequence.  it looks a bit weird, though...)

you can solve this by repeatedly adding individual strings, but that's rather
costly: first, your code will copy string 1 and 2 to a new string (let's call it
A).  then your code will copy A and string 3 to a new string B.  then your
code will copy B and string 4 to a new string C.  etc.  lots of unnecessary
copying.

the join method, in contrast, does it all in one operation.

</F> 






More information about the Python-list mailing list