문자열이 n자까지 반복되도록 하려면 먼저 전체 문자열을 n/len(s)번 반복하고 끝에 n%len(s) 문자를 추가할 수 있습니다. 예를 들어,
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) 이것은 출력을 줄 것입니다:
'asdfasdfas'
문자열에 '*' 연산을 사용하여 문자열을 반복할 수도 있습니다. 예를 들어,
def repeat_n(string_to_expand, n):
return (string_to_expand * ((n/len(string_to_expand))+1))[:n]
repeat_n('asdf', 10) 이것은 출력을 줄 것입니다:
'asdfasdfas'