Python 3.x 从具有索引的文本中删除多个子字符串
我有一个很长的文本,我正在尝试使用开始和结束索引删除多个子字符串。这里的问题是,当我从原始文本中删除第一个子字符串时,其余的开始和结束索引将无效。最有效的方法是什么Python 3.x 从具有索引的文本中删除多个子字符串,python-3.x,Python 3.x,我有一个很长的文本,我正在尝试使用开始和结束索引删除多个子字符串。这里的问题是,当我从原始文本中删除第一个子字符串时,其余的开始和结束索引将无效。最有效的方法是什么 def remove_substrings(text, indexes): ''' indexes is a list containing start and end indexes. indexes = ["3 5", "7 8"] '''
def remove_substrings(text, indexes):
'''
indexes is a list containing start and end indexes.
indexes = ["3 5", "7 8"]
'''
return text
不要立即删除子字符串,而是使用另一个变量并向其附加子字符串
def remove_substrings(text, indexes):
'''
indexes is a list containing start and end indexes.
indexes = ["3 5", "7 8"]
'''
newText = ""
i = 0
for index in indices:
j = int(index[0])
newText += text[i:j]
i = int(index[-1]) + 1
return newText
上述代码示例-文本:“abcdef…z”(所有英文字母)
索引:[“3 5”,“7 8”]
预期输出:除“d、e、f”(索引:3至5)和“h、i”(索引7至8)外的所有字母表。
字符串newText将在第一次迭代中从a到c追加值,然后在第二次迭代中从g追加值,依此类推。不是从
从左到右
删除子字符串,而是从从右到左
删除子字符串。这种方法将确保左侧的索引保持不变。虽然它会解决你的问题,但有更有效的方法可以做到这一点
def remove_substrings(text, indexes):
'''
indexes is a list containing start and end indexes.
indexes = ["3 5", "7 8"]
'''
int_indexes = []
for idx in indexes:
s1,s2 = idx.split()
int_indexes.append([int(s1), int(s2)])
int_indexes.sort()
int_indexes.reverse()
for idx in int_indexes:
text = text[0:idx[0]] + text[idx[1]+1:]
return text
如果索引未排序,则必须首先将其转换为整数。
试一试
第一个for循环可由列表COMMPRESSION替换,如下所示:
int_index=[[int(idx.split()[0]),int(idx.split()[1])]用于索引中的idx]
text = "0123456789012345"
print(remove_substrings(text, ["3 5", "10 12", "7 8"]))