135

7
+4  Q:

## Repeat string to certain length

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?

+5  A:
def repeat_to_length(string_to_expand, length):
return (string_to_expand * ((length/len(string_to_expand))+1))[:length]
+1  A:

Repeating a string a fixed number of times is a built-in operation:

'abc' * 7

So, just calculate the number of repeats you need to reach the length you want, and put that on the RHS. You'll then need to trim it to the right length.

(It appears that this is what the other answer does, but a little bit more explanation seemed useful.)

yah I misunderstood the question, see edit
A:

How about string * (length / len(string)) + string[0:(length % len(string))]

`length / len(string)` needs to be wrapper in parenthesis, and you're missing the last `]`.
A:

This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rpt string increases.

def repeat(rpt, length):
return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]
+6  A:
from itertools import cycle, islice
def srepeat(string, n):
return ''.join(islice(cycle(string), n))
+4  A:
def rep(s, m):
a, b = divmod(m, len(s))
return s * a + s[:b]
definitely the nicest looking so far. +1
+2  A:

Yay recursion!

def trunc(s,l):
if l > 0:
return s[:l] + trunc(s, l - len(s))
return ''

Won't scale forever, but it's fine for smaller strings. And it's pretty.

I admit I just read the Little Schemer and I like recursion right now.