[Tutor] string.join()

A.T.Hofkamp a.t.hofkamp at tue.nl
Mon Nov 3 17:01:27 CET 2008


Monte Milanuk wrote:
> Hello again,
> 
> Just looking for clarification on a point: the book I'm using is written
around Python v.2.3, and has an exercise using string.join(). Specifically, it
said to use string.join(msgList, ""), the object of which was to take the list
items in msgList and concatenate them using a blank or no character between.
After some work it did work as advertised, which is all well and good, but I
hit a bit of a snag along the way. I *think* I got it figgered out, but would
like some verification.

looks fine to me.
An experiment in Python confirmed that:

Python 2.3.4 (#1, Jul 25 2008, 14:24:21)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import string
 >>> string.join(['a', 'b', 'c'], '-')
'a-b-c'

each value in the list gets seperated from other value(s) by the seperator 
string ("-" in this case).

neighborhood so to speak maybe I should learn to do things the 'new' way. It
took me a while to get from string.join(words[, sep]) to str.join()... which
almost immediately puked and didn't work. After a while longer, I finally
noticed somewhere that 'str' was supposed to be the string used for the
separator, so I use ''.join(msgList), which seems to work (or at least give
identical output) in this case.

Correct too:

 >>> '-'.join(['a', 'b', 'c'])
'a-b-c'

This is indeed the recommended way of joining strings.


Sincerely,
Albert


More information about the Tutor mailing list