← Back to all posts
hey everybody

Hi everybody. It's me again. And I'm still stuck on the same code despite all your effort to help me. I'm sorry. But could someone please explain to me why this what I'm currently doing isn't working. I honestly don't understand. Here's the link again, but I made a few changes.

Answered by a5rocks (787) [earned 5 cycles]
a5rocks (787)

Here is something that should work. It uses modular arithmetic to find the third character, and uses continue to skip an interation. Both these are great tools, and I think you should check them out. Anyway, here :

``````start = input('Your string? ')
end = ''
for i in range(len(start)):
if i%3 == 2:
continue
end += start[i]
print(end)``````

Another thing is that you should join the repl.it discord (https://discord.gg/XadDsju), in which you would be able to get more comprehensive help.

Nanashi (7)

@a5rocks Extremely close, just that the question specifies deletion of indices divisible by 3. Yours is the solution for deletion of every third character, though to be honest that sounds like a more likely problem.

``````input    0123456789abcdefghij
i%3==0    12 45 78 ab de gh j
i%3==2   01 34 67 9a cd fg ij``````
a5rocks (787)

@Nanashi Oh sorry, must have misread the question. Good catch though :D

+1

Nanashi (7)

As of writing, you have this:

``````s = input()
x = 0

for i in range(len(s)):
if x > len(s):
break
else:
l = s[x]
s2 = s.replace(l,'')
x += 3
print(s2)``````

And you are getting `IndexError: string index out of range`. Your code will actually run on a string of length 7 or 8 but not 6 or multiples of 3. Why? When `x` becomes 6, `l` tries to become `s`, meaning the character from indices 6 to 7 (equivalent to `s[6:7]`), but `s` has length of 6 not 7 therefore the index is out of range. To stop it, break `if x >= len(s)`.

There are more problems, though. You don't want to use `replace()` because it will replace every instance of the substring. With your code, input "0011" outputs "00".

Also, `s` itself is never changing, so `s2` is being assigned to the same string with a slightly different action upon each iteration. `# [...] is supposed to delete every character who's index is divisible by three. So, basically every third number including the first.` With your code, input "01234" outputs "0124" when you want "124".

*I'm busy atm and will check back later.

You can use `i` in `for i in range(len(s)):` as the index and have a new string take `s[i]`:

``````s = input("Input: ")
s2 = ""

for i in range(len(s)):
if i % 3 != 0:
s2 = s2 + s[i]
print(s2)``````

% is modulo (remainder of division). This is saying to add `s[i]` if the index is not evenly divisible by 3.

String slicing also works and is closer to your approach:

``````s = input("Input: ")
x = 0

while x < len(s):
s = s[0:x] + s[x+1::]
x += 2
print(s)``````