0
symbols =['a','b','c']
for i in range(len(symbols)):
        formula= 'X~ age +' +symbols[i]+ '+'
        print(formula)

This will give an output like:

X~ age+ a+
X~ age + b +
X~ age + c + 

But I need the output to be :

X~ age+a 
X~ age+a+b 
X~ age +a +b+c 
3
  • What is your question? Commented Mar 7, 2015 at 14:08
  • 2
    Are the extra spaces in the last line of the output an absolute requirement? Commented Mar 7, 2015 at 14:20
  • @Paul Rooney no not at all its just a typo Commented Mar 7, 2015 at 17:02

5 Answers 5

1

The way to do this in general is to accumulate.

text = 'starter'
for symbol in symbols:
    text += symbol
    text += '+'
    print(text)

Because this is such a basic question I am not going to write out code that does exactly what you asked for. You should be able to figure out how to modify the above to do what you want.

Sign up to request clarification or add additional context in comments.

Comments

1

I am not exactly sure what you really want to do, but what about this:

items = ""
for elem in symbols:
    items = "{}{}".format(items, elem)
    print "X~ " + items

( it seems that you want to concat the elements of your array for each iteration; at least that is how I read your question)

1 Comment

Probably because your code prints X~ aX~ abX~ abc. You need to add the +'s in somewhere
0

You need to keep track of the previous strings seen.

symbols =['a','b','c']
prev = "+ "
for i in symbols:
        formula = 'X~ age {} {}'.format(prev,i)
        print(formula)
        prev += i + " + "

X~ age +  a
X~ age + a +  b
X~ age + a + b +  c

If you don't want spaces just remove them:

symbols =['a','b','c']
prev = "+"
for i in symbols:
      print('X~ age{}{}'.format(prev, i))
      prev += i + "+"

X~ age+a
X~ age+a+b
X~ age+a+b+c

You can also just iterate over the symbols directly, forget about indexing.

Comments

0
symbols =['a','b','c']
formula='X~ age'
for i in range(len(symbols)):
        formula= formula + '+' + symbols[i]
        print(formula)

Assuming that the spaces in X~ age +a +b+c between +a and +b was by mistake.. else.. I dont find some pattern here and you need to loop again to print it that way..

Comments

0

symbols = ['a','b','c']

output = "X~ age"

for i in range(len(symbols)):

if i != len(symbols) - 1:
    output = output + "+" + str(symbols[i])
    print output
else:
    output = "X~ age"
    output = output + " +" + str(symbols[0]) + " +" + str(symbols[1]) + "+" + str(symbols[2])
    print output

X~ age+a

X~ age+a+b

X~ age +a +b+c

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.