Skip to main content
 首页 » 编程设计

python之如何在python中将一个字符串复制到另一个字符串

2024年10月01日31dyllove98

我有两个字符串,s1 和 s2,我需要找出它们中是否有共同的字母并将其加倍,例如:

s1 = "Hello World" 
s2 = "lo" 
output = "Helllloo Woorlld" 

我的代码:

s2="lo" 
s1="Hello World" 
 
    def Str_dup(s1,s2): 
        s3=str() 
        d=dict() 
        for i in s2: 
            d[i]=True 
            print i 
            w=0 
        for w in range(len(s1)): 
            if d[s1[w]]: 
                s3[w]=s3[w]+s1[w] 
            else : 
                s3[w]=s1[w] 
        return s3 
    Str_dup(s1,s2) 

我收到一个错误:

    if d[s2[w]]: 
IndexError: string index out of range  

请您参考如下方法:

将字符串视为字符列表并使用列表理解来构造输出字符串会容易得多:

output = ''.join([c*2 if c in s2 else c for c in s1])