Page 1 of 1

Joining elements into a string

PostPosted: Sun Jun 07, 2009 10:59 am
by Charles
So Python let's you say:
Code: Select all
print ", ".join(items)

But I always found that rather strange as I think first about the items. Also it disallows having two separators such as ", " but with "and" for the last separator. So I'm planning:
print items.joined(", ")
print words.joined(", ", " and ")

I think one of the problems in Python is that there is no common base type for "list-like objects" but in .NET and JVM we can put an extension method on IEnumerable/Iterable.

Re: Joining elements into a string

PostPosted: Fri Jun 12, 2009 4:13 am
by Csaba
Hi, good idea, it would be easier to understand and nicer! Regards Csaba

Re: Joining elements into a string

PostPosted: Tue Jun 16, 2009 1:59 am
by Charles
This is now in the standard library as an extension to IEnumerable:
extend System.Collections.IEnumerable

def join(sep as String) as String
"""
Join the items in an IEnumerable collection separated by a string.
"""
test
assert ['a', 'b'].join('.') == 'a.b'
assert ['a'].join('.') == 'a'
assert [1, 2].join(', ') == '1, 2'
assert [1, 2].join('') == '12'
assert [].join('.') == ''
body
# ...

def join(sep as String, lastSep as String) as String
"""
Join the items in an IEnumerable collection with a separator string except for the last
two items; join them with the lastSep string
"""
test
assert ['a', 'b'].join(', ', ' and ') == 'a and b'
assert ['a', 'b', 'c'].join(', ', ' and ') == 'a, b and c'
assert ['a', 'b', 'c', 'd'].join(', ', ' and ') == 'a, b, c and d'
assert [1, 2, 3, 4].join(', ', ' and ') == '1, 2, 3 and 4'
assert [1].join('.', ':') == '1'
assert [1, 2].join('', '') == '12'
assert [].join('.', ':') == ''
body
# ...

Re: Joining elements into a string

PostPosted: Wed Jun 24, 2009 3:20 am
by jonathandavid
Very cool, this is much better than Python's approach IMHO.

I think it could be useful as well to have a version that takes the "initial" separator, so we can make:

assert [1, 2, 3, 4].join('{', ':', '}') == '{1:2:3:4}'