代码之家  ›  专栏  ›  技术社区  ›  shantanuo

在python中逐个替换字符串

  •  0
  • shantanuo  · 技术社区  · 3 年前

    我有一个字符串,我需要用“x”一次替换一个“e”。例如:。

    x = "three"
    

    则预期输出为:

    ("thrxe", "threx")
    

    如果我有3个字符要替换,例如。

    y = "threee"
    

    那么预期输出将是:

    ("thrxee", "threxe", "threex")
    

    我试过这个:

    x.replace("e", "x", 1)  # -> 'thrxe'
    

    但不确定如何返回第二个字符串 "threx" .

    3 回复  |  直到 3 年前
        1
  •  3
  •   cottontail    3 年前

    试试这个

    x = "threee"
    # build a generator expression that yields the position of "e"s
    # change "e"s with "x" according to location of "e"s yielded from the genexp
    [f"{x[:i]}x{x[i+1:]}" for i in (i for i, e in enumerate(x) if e=='e')]
    ['thrxee', 'threxe', 'threex']
    
        2
  •  3
  •   Nick SamSmith1986    3 年前

    你可以用发电机来代替 e 具有 x 按顺序遍历字符串。例如:

    def replace(string, old, new):
        l = len(old)
        start = 0
        while start != -1:
            start = string.find(old, start + l)
            if start != -1:
                yield string[:start] + new + string[start + l:]
    
    z = replace('threee', 'e', 'x')
    for s in z:
        print(s)
    

    输出:

    thrxee
    threxe
    threex
    

    注意,我对代码进行了概括,允许任意长度的匹配和替换字符串,如果不需要,只需替换 l ( len(old) )使用 1 .

        3
  •  1
  •   Sharim09    3 年前
    def replace(string,old,new):
        f = string.index(old)
        l = list(string)
        i = 0
        for a in range(string.count(old)):
            l[f] = new
            yield ''.join(l)
            l[f]=old
            try:
                f = string.index(old,f+1)
            except ValueError:
                pass
            i+=1
    
    
    z = replace('threee', 'e', 'x')
    for a in z:
        print(a)
    

    输出

    thrxee
    threxe
    threex