Home > database >  CodingBat Python string index out of range error
CodingBat Python string index out of range error

Time:01-16

I am currently doing a problem on coding bat called string_bits and have been debugging it using Thonny and putting the code into coding bat to see if it is correct. Right now I am getting an error with my code in codingbat that says string index out of range. The weird thing is when I run it in Thonny I don't get the error. What is happening here?

def string_bits(str):
  new_str = [str[0]]
  count = 0
  for letter in str[1:]:
    count  = 1
    if count % 2 == 0:
      new_str.append(letter)
  return "".join(new_str)

CodePudding user response:

Maybe the test trying some different kinds of input, and not only the obvious. for example if your input is an empty string: it will cause such an "out of range" error. Try to add input check before any operation on the string (which is actually an array)

like so:

def string_bits(str):
  # check input for empty string
  if str == "":
    # quit function if invalid input
    return ""
  new_str = [str[0]]
  count = 0
  for letter in str[1:]:
    count  = 1
    if count % 2 == 0:
      new_str.append(letter)
  return "".join(new_str)
  •  Tags:  
  • Related