【问题标题】:CodingBat Python string index out of range errorCodingBat Python 字符串索引超出范围错误
【发布时间】:2022-01-15 21:27:25
【问题描述】:

我目前正在做一个名为 string_bits 的编码 bat 问题,并一直在使用 Thonny 对其进行调试,并将代码放入编码 bat 中以查看它是否正确。现在,我在 codebat 中的代码出现错误,提示 string index out of range。奇怪的是,当我在 Thonny 中运行它时,我没有收到错误消息。这里发生了什么?

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)

【问题讨论】:

    标签: python string indexing compiler-errors


    【解决方案1】:

    也许测试尝试了一些不同类型的输入,而不仅仅是显而易见的。 例如,如果您的输入是一个空字符串:它将导致这样的“超出范围”错误。 尝试在对字符串(实际上是一个数组)进行任何操作之前添加输入检查

    像这样:

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2019-12-24
      • 2013-09-25
      相关资源
      最近更新 更多