首页 > 解决方案 > CodingBat 帮助。list.remove(x): x not in list 错误?不明白为什么这不起作用

问题描述

“给定一个非空字符串和一个 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*

标签: python

解决方案


你可以试试:

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

演示


推荐阅读