【问题标题】:CodingBat Help. list.remove(x): x not in list error? Not understanding why this is not workingCodingBat 帮助。 list.remove(x): x not in list 错误?不明白为什么这不起作用
【发布时间】:2020-03-01 08:02:35
【问题描述】:

"给定一个非空字符串和一个 int n,返回一个新字符串,其中索引 n 处的 char 已被删除。n 的值将是原始字符串中 char 的有效索引(即n 将在 0..len(str)-1 的范围内)。"

missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'

我的解决方案:

def missing_char(str, n):
  lst = list(str)
  lst.remove([n])
  return lst
*Compile problems:
list.remove(x): x not in list*

【问题讨论】:

  • 您的意思可能是lst.remove(n),但这不会像您想的那样。 remove 根据 element 而不是 index 删除。你需要的是pop()。但是不需要转换为列表,请改用切片
  • 命名变量str 是个坏主意,要小心。

标签: python


【解决方案1】:

你可以试试:

def missing_char(word, index):
    if len(word) > index:
        word = word[0 : index : ] + word[index + 1 : :]
        return word
    else:
        return "invalid index"

print(missing_char('kitten', 1))
# ktten

Demo

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 1970-01-01
    • 2021-01-21
    • 2020-07-11
    • 1970-01-01
    • 2021-11-03
    • 2022-06-28
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多