views:

99

answers:

2

Hi,

I have a list filter = ['a', 'b', 'c']. I need to frame the following string out of the list "item -a item -b item -c". Which is the most efficient way to do this? Usually the list filter contains 100 to 200 items and each would be of length 100 - 150. Wouldn't that lead to overflow? And what is the maximum length of the string supported?

+1  A: 

You can use join (I believe join is the same in Python 3.0):

>>> l = ['a','b','c']
>>> print ' item -'.join([''] + l)
>>> ' item -a item -b item -c'

>>> print ' item -'.join([''] + l).lstrip(' ') # eat the leading space
>>> 'item -a item -b item -c'
Nick D
Wouldn't `' item -'.join(l)` work just as well?
Dominic Rodger
You probably want to trim excess whitespace off the result too.
Dominic Rodger
@Dominic Rodger, yes we can trim the leading space. `join(l)` won't give the result that Prabhu wants. The string would start `'a item...'` instead of `'item -a...'`
Nick D
+3  A: 

A cleaner way to do this:

filter = ['a', 'b', 'c']
" ".join(["item -%s" % val for val in filter])

This works fine with large arrays, eg. filter = ['a'*1000] * 1000.

Glenn Maynard
Great solution. Thanks
Prabhu