The problem is a famous one! You can't fiddle with the thing you're iterating over. In your case you're fiddling with stringexp and iterating over it at the same time creating unpredictable results.
There are several ways to achieve the same result though:
- stringexp = stringexp.replace("+"," + ")
is the easiest. There are many powerful string methods which are well worth getting familiar with.
But supposing you really wanted to do it your way. There are several problems with your current code. Playing around on your command line is a helpful way of figuring this out. Also printing out the variables as you go helps clarify whether a variable is what you think it should be.
Problem 1: "for i in stringexp:" assuming that stringexp is a string, then i is going to take on the various characters in the string in turn.
- In [8]: for i in "hello, mum!":
-
...: print i
-
...:
-
...:
-
h
-
e
-
l
-
l
-
o
-
,
-
-
m
-
u
-
m
-
!
-
This means that stringexp[i] has no meaning. What you really mean to say is
But actually you want i to be a number. So you could do this as follows:
- for i in range(len(stringexp)):
or you could do it this way:
[code]In [10]: for i,char in enumerate("hello, mum!"):
print i, char
....:
....:
0 h
1 e
2 l
3 l
4 o
5 ,
6
7 m
8 u
9 m
10 !
/CODE]
But this leads to the next problem. Suppose you inserted two characters into your string. Then the indexing would be off for the next insertion! One way around that is to do it backwards. The other way is to keep track of how many insertions you've made and adjust for it.
Good luck!