Search code examples
pythonstringrepeat

Character repeating in a string


can you please tell me how to get every character in a string repeated using the for loop in python?my progress is as far as :

def double(str):
    for i in range(len(str)):
        return i * 2

and this returns only the first letter of the string repeated


Solution

  • I believe you want to print each character of the input string twice, in order. The issue with your attempt is your use of return. You only want to return the final string, not just a single repetition of one character from inside the loop. So you want your return statement to be somehow outside the for-loop.

    Since this sounds like a homework problem, try to figure out how to do that above before continuing below.

    Still stuck?

    Print each character in a string twice, in order:

    def double(str):
        outstr = ''
        for character in str:
            outstr = outstr + character + character
        return outstr
    

    Without using a for-loop:

    def double(str):
        return ''.join([c+c for c in str])