比较两个字符串并替换字母

2024-06-26 00:12:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我想编写一个函数mask(a, b),它包含两个字符串ab,并将字母更改为a中的*,顺序与它们在b中的出现顺序相同,则返回一个新字符串

例如,如果s1="How are you doing today"s2="hardod",则新字符串/更新的s1字符串应为"*ow **e you **ing to*ay"

有没有办法做到这一点

def mask(a,b):
    for ch in s2:
    
         s1 = s1.replace(ch, '*', 1)
    return s1

print(mask("How are you doing today", "hardod"))

然后我得到输出H*ll*, *ow **e you Anders?,这是错误的,因为它们应该依次替换,即b中的第一个字母应该替换a中出现在的第一个索引上的同一个字母,不再是,然后b应该继续到第二个字母ib,替换它出现的第一个索引上的同一个字母ia,不再是等


Tags: 函数字符串youtoday顺序字母maskch
2条回答

我会这样做:

def mask(a, b):
    start_index = 0
    for c in b:
        for i in range(start_index, len(a)):
            if c == a[i]:
                a = "".join((a[:i], "*", a[i+1:]))
                start_index = i+1
                break
    return a

您可以选择是否区分大小写

def replace(s, position, character):
    return s[:position] + character + s[position+1:]

def mask(a,b):
    indexb=0
    for indexa in range(0,len(a)):
         ch=a[indexa]
         if (ch.lower()==b[indexb]):
            a=replace(a,indexa,'*')
            indexb=indexb+1
            if (indexb==len(b)):
                indexb=0
    return a

print(mask("How are you doing today", "hardod"))

给予

*ow **e you **ing to*ay

相关问题 更多 >