如果您希望字符串重复n个字符,则可以首先将整个字符串重复n / len次,并在末尾添加n%len个字符。例如,
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'