在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 出院祝福语简短8字