-1

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

该函数应该接受一个字符串和索引列表,并返回一个新字符串,其中删除了这些索引之间的字符。

论据:

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

假设 start 和 end 都是有效的索引(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
4

4 回答 4

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
于 2018-10-01T01:56:42.137 回答
0

正如 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]

现在:

print(word)

对于所有解决方案,请重现:

white lap
于 2018-10-01T00:35:27.737 回答
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 )

这将输出指定的“ white lap ”。

于 2018-10-01T01:02:39.227 回答
0
''.join([w for i, w in enumerate(word) if i not in indices])

 'white lapo'
于 2018-10-01T00:53:15.217 回答