Forums

Joining elements into a string

General discussion about Cobra. Releases and general news will also be posted here.
Feel free to ask questions or just say "Hello".

Joining elements into a string

Postby Charles » Sun Jun 07, 2009 10:59 am

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.
Charles
 
Posts: 2515
Location: Los Angeles, CA

Re: Joining elements into a string

Postby Csaba » Fri Jun 12, 2009 4:13 am

Hi, good idea, it would be easier to understand and nicer! Regards Csaba
Csaba
 
Posts: 42

Re: Joining elements into a string

Postby Charles » Tue Jun 16, 2009 1:59 am

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
# ...
Charles
 
Posts: 2515
Location: Los Angeles, CA

Re: Joining elements into a string

Postby jonathandavid » Wed Jun 24, 2009 3:20 am

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}'
jonathandavid
 
Posts: 159


Return to Discussion

Who is online

Users browsing this forum: No registered users and 82 guests

cron