0

Here is my code, I want to do a conditional concatenation, my issue is that at the end of the for loop I have all variables starting with \n. To remove it I need to strip out each variable. I think there should be some batter way to handle this. Any suggestions would be appreciated.

foo = bar = remaining = ''
for i in ['foo', 'foo', 'hello', 'foo', 'tr', '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()
3
  • Why would you have difficulty removing the \n? Your own code is what places it in the output variables. There are a couple of ways you could tidy up that string concatenation to skip the newlines. Commented Sep 22, 2013 at 20:59
  • strip() only is not enough use the join method Commented Sep 22, 2013 at 21:00
  • @HeathHunnicutt i would like to know some some batter approch to handle this, my code is fully funtional but i think i have done an extra code to handle this satutation Commented Sep 22, 2013 at 21:02

2 Answers 2

6

Instead of building strings, build lists and '\n'.join then when you finish:

foos = []
bars = []
remaining = []
for i in ['foo', 'foo', 'hello', 'foo', 'tr', 'foo', 'bar', 'foo', 'el']:
    if 'foo' in i:
        foos.append(i)
    elif 'bar' in i:
        bars.append(i)
    else:
        remaining.append(i)

foo = '\n'.join(foos)
bar = '\n'.join(bars)
remaining = '\n'.join(remaining)
Sign up to request clarification or add additional context in comments.

2 Comments

@HeathHunnicutt: Simultaneity is subjective. But yes, I'll admit this was low hanging fruit, and I should have got it right first time
Hooray join(); much, much more efficient than successive concatenations
0
foo = ''
bar = ''
remaining = ''

_list = ['foo', 'foo', 'hello', 'foo', 'tr', 'foo', 'bar', 'foo', 'el']

for outer in xrange(len(_list)):
    for i, e in enumerate(_list):

        foo += '\n%s' % _list.pop(i) if 'foo' in e else ''
        bar += '\n%s' % _list.pop(i) if 'bar' in e else ''

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.