Here is the task . Given a string. Remove from it all the characters whose indices are divided by 3. The characters of the string are numbered starting from zero.
Here is the code.

s = str(input()) pos = 0 v = 0 while v != -1: v = s.find('', pos) k = s[v] if v % 3 == 0: s = s.replace(k, '') pos += 1 print(s) 

Here is a mistake.

 k = s[v]. IndexError: string index out of range. 

Explain, please, what is wrong with the code?

  • five
    to the question what is wrong with your code will be answered by other members of SO. I would advise you to immediately get used to a good style: s = ''.join(x for i,x in enumerate(s) if i%3) ;) - MaxU
  • one
    And you print(v, repr(s)) before the problem line - andreymal
  • What do you think will be equal to v after v = s.find ('', pos)? - Enikeyschik Nov.

3 answers 3

First, the team

 v = s.find('', pos) 

does the same thing as simple

 v = pos if pos <= len(s) else -1 

The problem is already here - when your string s is for example "abc" , it may happen that v == 3 , and the command k = s[v] turns into k = s[3] is an error, because s[3] does not exist .

Secondly, the team

 s = s.replace(k, '') 

your initial string s gradually shortened , so the next third position (to delete a character) will not be the same as in the original string .

     s = list(input()) del s[::3] print(''.join(s)) 

      It is possible so:

       s = input() print(''.join(s[i] for i in range(len(s)) if i % 3 != 0)) 
      • Kst, and mb add an example with enumerate? print(''.join(c for i, c in enumerate(s) if i % 3 != 0)) ? For cases when both indices and values ​​are needed right away, it is better suited than range :) - gil9red
      • @ gil9red, for some reason not. Although who prevents to use i, s[i] ? - Andrey