在Python中将字符串重复到一定长度的有效方法是什么?
如果您希望字符串重复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'
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短