[Python] Repeat string to certain length

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    What is an efficient way to repeat a string to a certain length? Eg: repeat('abc', 7) -> 'abcabca'

    Here is my current code:

    def repeat(string, length):
    cur, old = 1, string
    while len(string) < length:
    string += old[cur-1]
    cur = (cur+1)%len(old)
    return string


    Is there a better (more pythonic) way to do this? Maybe using list comprehension?

    Continue reading...

Compartilhe esta Página