Muốn string lặp đến n ký tự, lặp toàn bộ string n/len(s) lần và thêm n%len(s) ký tự cuối. Ví dụ:
def repeat_n(string, n):
l = len(s)
full_rep = n/l
# Construct string with full repetitions
ans = ''.join(string for i in xrange(full_rep))
# add the string with remaining characters at the end.
return ans + string[:n%l]
repeat_n('asdf', 10)
Output:
'asdfasdfas'
Cũng dùng phép * trên string lặp string. Ví dụ:
def repeat_n(string_to_expand, n):
return (string_to_expand * ((n/len(string_to_expand))+1))[:n]
repeat_n('asdf', 10)
Output:
'asdfasdfas'