将字符串重复到一定长度的有效方法是什么?例:repeat('abc', 7) -> 'abcabca'

这是我当前的代码:

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

有没有更好的(更python化的)方法来做到这一点?也许使用列表理解?


当前回答

也许不是最有效的解决方案,但肯定简短简单:

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

repstr("foobar", 14)

给“foobarfoobarfo”。关于这个版本的一件事是,如果length < len(string),那么输出字符串将被截断。例如:

repstr("foobar", 3)

给“foo”。

编辑:实际上令我惊讶的是,这比目前接受的解决方案('repeat_to_length'函数)更快,至少在短字符串上:

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

假设如果字符串很长,或者长度非常高(也就是说,如果字符串长度部分的浪费很高),那么它的性能就会很差。事实上,我们可以修改上面的内容来验证这一点:

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

其他回答

def rep(s, m):
    a, b = divmod(m, len(s))
    return s * a + s[:b]
def repeat_to_length(string_to_expand, length):
   return (string_to_expand * ((length/len(string_to_expand))+1))[:length]

python3:

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

这是非常python的:

newstring = 'abc'*5
print newstring[0:6]
from itertools import cycle, islice
def srepeat(string, n):
   return ''.join(islice(cycle(string), n))

也许不是最有效的解决方案,但肯定简短简单:

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

repstr("foobar", 14)

给“foobarfoobarfo”。关于这个版本的一件事是,如果length < len(string),那么输出字符串将被截断。例如:

repstr("foobar", 3)

给“foo”。

编辑:实际上令我惊讶的是,这比目前接受的解决方案('repeat_to_length'函数)更快,至少在短字符串上:

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

假设如果字符串很长,或者长度非常高(也就是说,如果字符串长度部分的浪费很高),那么它的性能就会很差。事实上,我们可以修改上面的内容来验证这一点:

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