2

I have two strings, s1 and s2, and I need to find if there are letters in common in both of them and make it double for example:

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

My code:

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)

I get an error on:

    if d[s2[w]]:
IndexError: string index out of range 
3
  • s1 is longer than s2, so obviously w is too big sometimes to get s2[w]. Also you can't modify a string as in s3[w]=.... You need to make a list of characters and then combine them into a string with ''.join(list_of_chars). Commented May 6, 2017 at 10:58
  • 1
    "string index out of the range"?! Please just copy and paste the literal text, it makes it far less likely you'll provide inaccurate information. Commented May 6, 2017 at 11:00
  • thnx a lot it works :) Commented May 6, 2017 at 11:46

1 Answer 1

2

It would be so much easier to treat the strings as lists of characters and use list comprehension to construct the output string:

output = ''.join([c*2 if c in s2 else c for c in s1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.