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.

Here's the link: https://repl.it/@FARHEENPALAGIRI/Delete-every-third-character

You are viewing a single comment. View All
Answered by a5rocks (782) [earned 5 cycles]
View Answer
Nanashi (7)

As of writing, you have this:

s = input()
x = 0

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

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[6], 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]

% 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