将字符串重复到一定长度的有效方法是什么?例: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化的)方法来做到这一点?也许使用列表理解?


当前回答

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

其他回答

并不是说这个问题没有足够的答案,而是有一个重复函数;只需要做一个列表,然后加入输出:

from itertools import repeat

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

这是一种使用列表理解的方法,尽管随着rpt字符串长度的增加,这种方法会越来越浪费。

def repeat(rpt, length):
    return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]

这是非常python的:

newstring = 'abc'*5
print newstring[0:6]
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]
def extended_string (word, length) :

    extra_long_word = word * (length//len(word) + 1)
    required_string = extra_long_word[:length]
    return required_string

print(extended_string("abc", 7))