Home » Python » Repeat string to certain length

Repeat string to certain length

Posted by: admin November 1, 2017 Leave a comment

Questions:

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?

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

Questions:
Answers:

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.)

Questions:
Answers:

This is pretty pythonic:

newstring = 'abc'*5
print newstring[0:6]

Questions:
Answers:
def rep(s, m):
    a, b = divmod(m, len(s))
    return s * a + s[:b]

Questions:
Answers:
from itertools import cycle, islice
def srepeat(string, n):
   return ''.join(islice(cycle(string), n))

Questions:
Answers:

i use this:

def extend_string(s, l):
    return (s*l)[:l]

Questions:
Answers:

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

Questions:
Answers:

Not that there haven’t been enough answers to this question, but there is a repeat function; just need to make a list of and then join the output:

from itertools import repeat

def rep(s,n):
  ''.join(list(repeat(s,n))

Questions:
Answers:

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.

Questions:
Answers:

Perhaps not the most efficient solution, but certainly short & simple:

def repstr(string, length):
    return (string * length)[0:length]

repstr("foobar", 14)

Gives “foobarfoobarfo”. One thing about this version is that if length < len(string) then the output string will be truncated. For example:

repstr("foobar", 3)

Gives “foo”.

Edit: actually to my surprise, this is faster than the currently accepted solution (the ‘repeat_to_length’ function), at least on short strings:

from timeit import Timer
t1 = Timer("repstr('foofoo', 30)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo', 30)", 'from __main__ import repeat_to_length')
t1.timeit()  # gives ~0.35 secs
t2.timeit()  # gives ~0.43 secs

Presumably if the string was long, or length was very high (that is, if the wastefulness of the string * length part was high) then it would perform poorly. And in fact we can modify the above to verify this:

from timeit import Timer
t1 = Timer("repstr('foofoo' * 10, 3000)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo' * 10, 3000)", 'from __main__ import repeat_to_length')
t1.timeit()  # gives ~18.85 secs
t2.timeit()  # gives ~1.13 secs

Questions:
Answers:

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]

Questions:
Answers:

Another FP aproach:

def repeat_string(string_to_repeat, repetitions):
    return ''.join([ string_to_repeat for n in range(repetitions)])