python - 给定不连续出现的索引列表,替换所有出现的 s 的子字符串 t 的 pythonic 方法是什么?

标签 python python-3.x algorithm replace substring

这段代码有一个错误。给定一个索引列表 inds,其中 old 已知出现(对于两个不同的索引不相交),以及一个 new 替换字符串,什么是结果字符串?

# Replace substring old with new in s at indices inds
def replace_substrings_at(self, inds, old, new):
    s = self._input
    inds = sorted(inds)
    res = s
    for i in inds:
        res = res[:inds[0]] + res[inds[0]:].replace(old, new, 1)
    return res    

问候。

我知道 str.replace() 有一个计数参数。但我不想替换所有出现的事件,只替换我指定的特定列表,它可以到处都是!


这是一个更好的版本,但有没有更简单的方法?

# Replace substring old with new in s at indices inds known to be disjoint w.r.t. old
def replace_substrings_at(self, inds, old, new):
    s = self._input
    inds = sorted(inds)
    res = s[:inds[0]]
    for k in range(len(inds)):
        i = inds[k]
        res += new
        if k + 1 < len(inds):
            res += s[i+len(old):inds[k+1]]
    return res   

最佳答案

下面的代码在替换发生的位置拆分字符串,然后将替换的部分重新连接在一起。这使用以 'other'.join(['hi ', ' is a this string of ', '']) 结尾的想法.

此代码假定替换范围是不相交的。那不是inds中的数字小于 len(old)从下一个。

def replace_substrings(s, inds, old, new):
    d = len(old)
    c = 0
    l = []
    for i in sorted(inds):
        l.append(s[c:i])
        c = i+d
    l.append(s[c:])
    return new.join(l)

使用与 TigerhawkT3 的回答相同的例子:

>>> replace_substrings('hi this is a this string of this', (3, 28), 'this', 'other')
'hi other is a this string of other'

对于较长的字符串,这会花费更少,因为它不使用 list(s)这可能导致字符串每个字符串字节占用 10 到 50 个字节。我什至不想考虑执行 l[i:i+d] = new 时进行的二次复制什么时候len(old) != len(new) .

关于python - 给定不连续出现的索引列表,替换所有出现的 s 的子字符串 t 的 pythonic 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684701/

相关文章:

python - 将列表中长度不等的值追加到字典中

python-3.x - pip 搜索和 pip 安装出现错误

python - Python中的费马大定理算法

algorithm - 不吉利的数字

python - 打开终端运行命令python

python - 需要有关 python 异常处理的帮助

python - 抑制 Python 命令的终端输出

python - 在 Python 中计算以 10 为底的对数的算法

python - 使用 python 遍历文件时忽略错误引发

python - 将具有重复字符的字符串拆分为列表