string.join() syntax quirky?

Werner Schiendl ws-news at gmx.at
Thu Nov 22 14:24:07 EST 2001


Hi,

"Erik Johnson" <ejohnso9 at earthlink.net> wrote in message
news:3BFD49D8.F7A4C6CC at earthlink.net...
....
> s = "".join(l)
>
>     This works fine, but it seems syntactically backwards to me:
>
> # s = l.join("")
>
> makes much more sense to me. The thingy I want to do something to is my
> list. I am just trying to learn Python, so no doubt there will be some
> Python things I will just have to get used to, but is there a logical
> reason why it was implemented as a string method rather than a list
> method? Does it seem backwards to you or does it make intuitive sense to
> you? Comments? (other than of the "it's moot" flavor)
>
....

For one thing, "".join does not just work for lists. It also works for all
other sequences.
e. g.

>>> "-".join("Works with all sequences")
'W-o-r-k-s- -w-i-t-h- -a-l-l- -s-e-q-u-e-n-c-e-s'

or with your own classes, if they act as sequences:


>>> class TestSeq:
...  def __init__(self, num_item):
...   self._num_item=num_item
...  def __getitem__(self, index):
...   if 0 <= index <= self._num_item:
...    return str(index)
...   else:
...    raise IndexError, "Index out of range."
...  def __len__(self):
...   return self._num_item
...
>>> t = TestSeq(20)
>>> "#".join(t)
'0#1#2#3#4#5#6#7#8#9#10#11#12#13#14#15#16#17#18#19#20'


Why not just read the above as 'use _"#"_ to _join_ the items in _t_ into a
string'?
Then it sounds a lot more logical.

best regards
Werner





More information about the Python-list mailing list