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?
3 Answers
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' 2 Comments
Dominic Rodger
You probably want to trim excess whitespace off the result too.
Nick Dandoulakis
@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...'
filteras variable name. "filter" is a Python function.filterusually are highlighted by the IDE.