如何在不使用del的情况下从列表中删除多个元素

时间:2018-10-01 00:16:48

标签: python

如何从字符串中删除指定范围?

该函数应采用一个字符串和索引列表,并返回一个新字符串 删除那些索引之间的字符。

参数:

(ie. between 0 and len(my_str), inclusive)

假定开始和结束都是有效索引start <= end,并且该(ie. [0, 10] will come before [15, 20])。假定范围从最早的del到最新的word = "white laptop" indices = [9, 11] print(remove_range(word, indices) >>> white lap 进行排序,并且范围不会重叠。

我不知道如何开始,关键是不要使用{{1}}语句

示例:

{{1}}

4 个答案:

答案 0 :(得分:1)

如果您的目标是创建一个函数,则可以传递索引,并使用这些索引对传递给函数的字符串进行切片,所需结果的索引也将为9, 12

def remove_indices(s, indices):
    return s[:indices[0]] + s[indices[1]:]

s = 'white laptop'
indices = [9, 12]

print(remove_indices(s, indices))
white lap

答案 1 :(得分:0)

如RafaelC所说,使用切片:

onCreate

或者另一种切片方式是:

word=word[:indices[0]] + word[indices[1]+1:]

或者另一种方式是:

word=word.replace(word[indices[0]:indices[1]+1],'')

现在:

word=word.replace(word[slice(*indices)],'')[:-1]

对于所有解决方案,请复制:

print(word)

答案 2 :(得分:0)

''.join([w for i, w in enumerate(word) if i not in indices])

 'white lapo'

答案 3 :(得分:0)

您可以使用列表理解。

word = "white laptop"
indices = [9, 11]
output = ''
output = [word[index] for index in range(0, len(word)) if (index < indices[0] or index > indices[1])]
output = ''.join(map(str, output))
print(output )

这将按照指定输出'白圈'。

相关问题