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

Python 如何在不使用del的情况下从列表中删除多个元素,python,Python,如何从字符串中删除指定的范围 函数应该获取一个字符串和索引列表,并返回一个新字符串 删除这些索引之间的字符 论据: my_str (str): The string to be modified. ranges (list): A list of [start, end] indices. 假设开始和结束都是有效的索引(即介于0和len(my_str),包括在内),并且start如RafaelC所说,使用切片: word=word[:indices[0]] + word[indices[1]+

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

函数应该获取一个字符串和索引列表,并返回一个新字符串 删除这些索引之间的字符

论据:

my_str (str): The string to be modified.
ranges (list): A list of [start, end] indices.

假设开始和结束都是有效的索引
(即介于0和len(my_str),包括在内)
,并且
start如RafaelC所说,使用切片:

word=word[:indices[0]] + word[indices[1]+1:]
或者另一种切片方式是:

word=word.replace(word[indices[0]:indices[1]+1],'')
或者另一种方式是:

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

对于所有解决方案:

white lap

你可以使用列表理解

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 )
word=“白色笔记本电脑”
指数=[9,11]
输出=“”
如果(索引<索引[0]或索引>索引[1]),则输出=(0,len(word))范围内索引的[word[index]
输出=''.join(映射(str,输出))
打印(输出)

这将输出指定的“白圈”。

如果您的目标是创建一个函数,您可以传递索引并使用这些索引将传递到函数中的字符串切分,并且期望结果的索引将是
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))

请给出更多的上下文,特别是您现在对Python字符串的理解程度。例如,您了解Python的切片表示法吗?连接?使用切片
word[:索引[0]]+word[索引[1]+1:][/code>可以简单地将:s=s[:索引[0]]+s[索引[1]:]。这应该可以。但如果有必要。。。。写得好,python的方式。@Eswar是的,正在处理OPs请求,但实际上同意,不需要函数定义
''.join([w for i, w in enumerate(word) if i not in indices])

 'white lapo'
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 )
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