patternpythonMajor
Join List with Separator
Viewed 0 times
withlistseparatorjoin
Problem
I was implementing something similar to Python's join function, where
returns
e.g.,
I was implementing something similar and was wondering, what is a good pattern to do this? Because there is the issue of only adding the separator if it is not the last element
I'm quite happy with this, but is there a canoncial approach?
join([a1, a2, ..., aN], separator :: String)returns
str(a1) + separator + str(a2) + separator + ... + str(aN)e.g.,
join([1, 2, 3], '+') == '1+2+3'I was implementing something similar and was wondering, what is a good pattern to do this? Because there is the issue of only adding the separator if it is not the last element
def join(l, sep):
out_str = ''
for i, el in enumerate(l):
out_str += '{}{}'.format(el, sep)
return out_str[:-len(sep)]I'm quite happy with this, but is there a canoncial approach?
Solution
Strings in Python are immutable, and so
And so, the best way to join an iterable by a separator is to use
If you want to do this manually, then I'd accept the \$O(n^2)\$ performance, and write something easy to understand. One way to do this is to take the first item, and add a separator and an item every time after, such as:
'string a' + 'string b' has to make a third string to combine them. Say you want to clone a string, by adding each item to the string will get \$O(n^2)\$ time, as opposed to \$O(n)\$ as you would get if it were a list.And so, the best way to join an iterable by a separator is to use
str.join.>>> ','.join('abcdef')
'a,b,c,d,e,f'If you want to do this manually, then I'd accept the \$O(n^2)\$ performance, and write something easy to understand. One way to do this is to take the first item, and add a separator and an item every time after, such as:
def join(iterator, seperator):
it = map(str, iterator)
seperator = str(seperator)
string = next(it, '')
for s in it:
string += seperator + s
return stringCode Snippets
>>> ','.join('abcdef')
'a,b,c,d,e,f'def join(iterator, seperator):
it = map(str, iterator)
seperator = str(seperator)
string = next(it, '')
for s in it:
string += seperator + s
return stringContext
StackExchange Code Review Q#162809, answer score: 29
Revisions (0)
No revisions yet.