首页 > 解决方案 > 尝试在python中一次搜索2个字符

问题描述

我刚刚回到python,我试图通过一个字符串一次搜索两个字符,然后用其他东西替换它们。例如在字符串“aah”中搜索字符串“aa”并将其替换为其他内容,例如“xx”,但是当我尝试运行它时,它说类型必须是字符串,而不是 int。这是我的代码,任何帮助将不胜感激,谢谢

test = input("enter words to encrypt\n")
#print(test)

#change a letter
def changea(test):
    #print(test)
    outp = ""
    for i in test:
        if i & i+1  == "aa":
            outp += "x"
        else:
            outp += i

    print(outp)
changea(test)

标签: pythonpython-3.xfor-loop

解决方案


理想情况下,您应该使用replaceor re.sub。但是,如果您致力于使用循环,您可以尝试以下方法:

def changea(test):
    pairs = zip(test, test[1:] + "$")
    out = ""
    for x, y in pairs:
        if x == "a" and y == "a":
            out += "x"
            next(pairs) # Skip the next iteration
        else:
            out += x
    return out

changea("Maary haad aa little laamb")
#'Mxry hxd x little lxmb'

推荐阅读