I am not quite sure why this is happening. I am trying to remove everything between the commas, but it seems to be doing something weird.
import re
jsontext = '123,0test123,456,4test567,789'
for log in re.finditer('test', jsontext):
print jsontext
logstart = jsontext.rfind(",",0,log.start())
logend = jsontext.find(",",log.start())
jsontext = jsontext[:logstart] + jsontext[logend+1:]
print logstart
print logend
print '\n'
print jsontext
print '\n---end---\n'
it is producing
123,0test123,456,4test567,789
3
12
123456,4test567,789
---end---
123456,4test567,789
15
-1
123456,4test567123456,4test567,789
---end---
which leaves with
123456,4test567123456,4test567,789
but I am expecting the end result of
123456789
Why does this happen and how can I fix it?
Fixed this by adding the following:
import re
x = 0
jsontext = '123,0test123,456,4test567,789'
while x == 0:
log = jsontext.find('test')
if log <> -1:
logstart = jsontext.rfind(",",0,log)
logend = jsontext.find(",",log)
jsontext = jsontext[:logstart] + jsontext[logend+10:]
else:
x = 1
print jsontext
You may have fixed it but your problem is basically the fact that
for log in re.finditer('test',jsontext)
continues to use the original jsontext and not the new value for jsontext.
You can prove this by using this implementation:
import re
jsontext = '123,0test123,456,4test567,789'
for log in re.finditer('test', jsontext):
log = re.finditer('test',jsontext).next()
print jsontext
print log.start()
logstart = jsontext.rfind(",",0,log.start())
logend = jsontext.find(",",log.start())
jsontext = jsontext[:logstart] + jsontext[logend+1:]
print logstart
print logend
print '\n'
print jsontext
print '\n---end---\n'
You need to do this in a while loop, not in a for loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.