Nếu bạn muốn chuỗi lặp lại thành n ký tự, thì trước tiên bạn có thể lặp lại toàn bộ chuỗi thành n / len (s) lần và thêm n% len (s) ký tự vào 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) Điều này sẽ cho kết quả:
'asdfasdfas'
Bạn cũng có thể sử dụng thao tác '*' trên chuỗi để lặp lại chuỗi. Ví dụ:
def repeat_n(string_to_expand, n):
return (string_to_expand * ((n/len(string_to_expand))+1))[:n]
repeat_n('asdf', 10) Điều này sẽ cho kết quả:
'asdfasdfas'