This is a code I wrote for removing commas and full stops from a string
forbidden=(",",".")
text=input("Your sentence")
for i in range(0,len(text)):
if text[i] in forbidden:
text=text.replace(text[i],'')
i-=1
print text
My input was a,n
But it gives an error saying that string index is out of range
Could anyone explain why?
I see two problems:
len(text)
is calculated exactly once at the beginning of the loop. The fact that text
shrinks as you iterate over it, doesn't have any impact on what values i
will have later on.i
within your loop has no effect on the value of i
in the next iteration. Python simply steamrolls over the old value without looking at it.If you're absolutely committed to implementing this algorithm by iterating over the indices of text
, then using a while
loop would resolve both of these problems. A while
loops' condition evaluates at every iteration, and you have full control over the value you're incrementing/decrementing.
forbidden=(",",".")
text=raw_input("Your sentence: ")
i = 0
while i < len(text):
if text[i] in forbidden:
text=text.replace(text[i],'')
else:
i+=1
print text
Output:
Your sentence: foo,bar,baz.qux,troz,zort.
foobarbazquxtrozzort
... But if you're open to a different approach, it would save you a lot of effort if you iterated over the forbidden characters instead of text
.
forbidden=(",",".")
text=raw_input("Your sentence: ")
for c in forbidden:
text = text.replace(c, "")
print text