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


当前回答

这是非常python的:

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

其他回答

c = s.count('a')    
div=n//len(s)    
if n%len(s)==0:
    c= c*div
else:
    m = n%len(s)
    c = c*div+s[:m].count('a')
print(c)
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))

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

另一种FP方法:

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

当前打印(f"{'abc'*7}")生成:

abcabcabcabcabcabcabc