0

I've been assigned with the task of writing a program that triples all the letters in a string (ex: triple("Hello") should output "HHHeeelllooo")

After some time being stuck on this:

def triple(s) :
    new = ""
    i = 0
    for l in s[i]:
        new += l * 3
        i += 1
    return new

I solved rewriting it like this, which works:

def triple(s):
    new = ""
    i = 0
    for i in range(len(s)):
        new += s[i]*3
    return new

but, even though I found a solution, it would be really important to me to understand why the first version doesn't work, in order to avoid being stuck again in the future.

Thank you in advance to anyone who's willing to help me understand what was wrong in my logic.

j p
  • 1
  • 1
    `s[i]` is only evaluated once, and you're then looping over all characters in `s[i]`, which is just a single character. You just need `for l in s: ...`. No `i`, no `range`. – deceze Jan 06 '23 at 15:17

0 Answers0