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

标签 python

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

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

关于python - 如何通过它们在 Python 中的位置删除多个子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251233/

相关文章:

python - 使用 Python 构建动态 HTML 电子邮件内容

Python解析原始电子邮件并获取正文的文本内容

python - 我怎样才能缩短他的代码? (多个文件路径)

python - 在 2 个数组之间移动均方误差 'valid' ,它们完全重叠

python - argparse参数顺序

Python onclick 按钮小部件返回对象

python - 如何在多进程中从 python 调用 shell 脚本?

python - Python 中 sum() 的时间复杂度是多少?

python - 矫正倾斜的矩形图片和菱形形状

python - django.core.exceptions.ImproperlyConfigured : Could not resolve URL for hyperlinked relationship using view name "user-detail"