Is there an equivalent str.replace for the sequence as a whole?

Is there a method similar to str.replace that can do the following:

>> replace(sequence=[0,1,3], old=[0,1], new=[1,2]) 
[1,2,3]

It should really act like a str.replace: replace the "piece" of the sequence with another sequence, and not display the elements of the "old" with "new". Thank:)

+4
source share
2 answers

No, I'm afraid there is no built-in function that does this, however you can create your own!

, , - len(old). , == old, , , new list - old, @OmarEinea.

def replace(seq, old, new):
    seq = seq[:]
    w = len(old)
    i = 0
    while i < len(seq) - w + 1:
        if seq[i:i+w] == old:
            seq[i:i+w] = new
            i += len(new)
        else:
            i += 1
    return seq

, :

>>> replace([0, 1, 3], [0, 1], [1, 2])
[1, 2, 3]
>>> replace([0, 1, 3, 0], [0, 1], [1, 2])
[1, 2, 3, 0]
>>> replace([0, 1, 3, 0, 1], [0, 1], [7, 8])
[7, 8, 3, 7, 8]
>>> replace([1, 2, 3, 4, 5], [1, 2, 3], [1, 1, 2, 3])
[1, 1, 2, 3, 4, 5]
>>> replace([1, 2, 1, 2], [1, 2], [3])
[3, 3]

@user2357112, for-loop list, a while.

+5

, eval() Ned:

import re
import ast

def replace(sequence, old, new):
    sequence = str(sequence)
    replace_s=str(str(old).replace('[', '').replace(']', ''))
    if '.' in replace_s:
        replace_ss=list(replace_s)
        for j,i in enumerate(replace_ss):
            if i=='.':
                try:
                    replace_ss[0]=r"\b"+ replace_ss[0]
                    replace_ss[j]=r".\b"
                except IndexError:
                    pass
        replace_s="".join(replace_ss)


    else:

        replace_s = r"\b" + replace_s + r"\b"


    final_ = str(new).replace('[', '').replace(']', '')
    return ast.literal_eval(re.sub(replace_s, final_, sequence))





print(replace([0, 1, 3], [0, 1], [1, 2]))

:

[1, 2, 3]
0

Source: https://habr.com/ru/post/1692886/


All Articles