在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'
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短