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
-
What is your question?oridamari– oridamari2015年03月07日 14:08:07 +00:00Commented Mar 7, 2015 at 14:08
-
2Are the extra spaces in the last line of the output an absolute requirement?Paul Rooney– Paul Rooney2015年03月07日 14:20:02 +00:00Commented Mar 7, 2015 at 14:20
-
@Paul Rooney no not at all its just a typoShiva Prakash– Shiva Prakash2015年03月07日 17:02:58 +00:00Commented Mar 7, 2015 at 17:02
5 Answers 5
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.
Comments
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
X~ aX~ abX~ abc. You need to add the +'s in somewhereYou 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
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
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