Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to do a conditional concatenation. My issue is at the end of the for-loop. I have all variables starting with \n for removing this, and I need to strip out each variable. I think there should be a better way to handle this. Any suggestions would be appreciated.

foo = bar = remaining = ''
for i in ['foo', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'el']:
    if 'foo' in i:
        foo += '\n%s' % i
    elif 'bar' in i:
        bar += '\n%s' % i
    else:
        remaining += '\n%s' % i
foo = foo.strip()
bar = bar.strip()
remaining = remaining.strip()
share|improve this question

2 Answers

Using proper lists and joining only at the end is the trick.

foo,bar,remaining = [],[],[]
for i in ['foo', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'el']:
    (foo if 'foo' in i else bar if 'bar' in i else remaining).append(i)
foo =       '\n'.join(foo)
bar =       '\n'.join(bar)
remaining = '\n'.join(remaining)
print(foo,bar,remaining)
share|improve this answer

You could use a dictionary comprehension for this. The following does almost what you are asking for, and is easily expandable to include other string conditions as needed.

searches = 'foo', 'bar'
items = 'foo', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'el'
results = {search: [i for i in items if search in i] for search in searches}
results['remaining'] = [i for i in items if not any(search in i for search in searches)]
for search, result in results.items():
    print search, ': '
    print '\n'.join(result)

(The difference will be apparent if any of your items contain both 'foo' and 'bar')

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.