I'm trying to do this:
input: "4of Fo1r pe6ople g3ood th5e the2"
output: "Fo1r the2 g3ood 4of th5e pe6ople"
Using this code:
test = "4of Fo1r pe6ople g3ood th5e the2"
test = test.split()
x = 0
for i in test:
x = re.search("[1-9]", i)
x = int(x.group(0))-1
test.insert(x, test.pop(test.index(i)))
But for some reason the last line in the For loop ruins the outputs of x (which are the new indexes for the elements in the list of strings).
Before the last line (printing x after each iteration):
3
0
5
2
1
After the last line (printing x after each iteration):
3
5
3
3
1
5
CodePudding user response:
When you use the insert method inside a for loop it makes those updates during the iteration, thus changing the values at each index with every call.
If you add print(test)
at the end of each iteration you should see what I mean. One way to fix this problem is to create a list with the same length as test
and fill it with each iteration. For example:
test = "4of Fo1r pe6ople g3ood th5e the2"
test = test.split()
x = 0
new_list = [0] * len(test)
for i in test:
x = re.search("[1-9]", i)
x = int(x.group(0))-1
new_list[x] = i