Skip to main content
 首页 » 编程设计

python之如何通过它们在 Python 中的位置删除多个子字符串

2025年05月04日20pander-it

我有一个字符串,我有一个需要删除的子字符串的位置列表:

text = 'ab cd ef gh' 
positions = [[2, 5], [8, 11]] 

列表的每个元素都包含子字符串的开始和结束位置。结束位置不包括在内,开始位置包括在内。所以字符串应该被转换为:

text = 'ab ef' 

位置列表的长度是未知的,所以灵魂不能只是硬编码。

有什么有效的方法可以按位置删除多个子串吗?位置不能重叠。

请您参考如下方法:

字符串不可变,因此就地删除是不行的。连续连接不是最优的。

您可以将字符串转换为列表,这样它就可以变异,并通过删除每个不需要的切片来简单地删除所需的位置。使用 str.join重新创建您的字符串:

text = 'ab cd ef gh' 
 
lst = list(text) 
for i in positions[::-1]: # iterate from behind so index does not shrink inwards 
    del lst[slice(*i)] 
 
text = ''.join(lst) 
print(text) 
# 'ab ef' 

请注意,文档还建议将不可变类型的转换转换为列表作为最佳实践:

Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

  1. if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete