在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 红包祝福语简短10字
18 周六早晨祝福语简短