将字符串重复到一定长度 [英] Repeat string to certain length
本文介绍了将字符串重复到一定长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将字符串重复到特定长度的有效方法是什么?例如: repeat('abc', 7) ->'abcabca'
What is an efficient way to repeat a string to a certain length? Eg: repeat('abc', 7) -> 'abcabca'
这是我当前的代码:
def repeat(string, length):
cur, old = 1, string
while len(string) < length:
string += old[cur-1]
cur = (cur+1)%len(old)
return string
有没有更好(更pythonic)的方法来做到这一点?也许使用列表理解?
Is there a better (more pythonic) way to do this? Maybe using list comprehension?
推荐答案
def repeat_to_length(string_to_expand, length):
return (string_to_expand * ((length/len(string_to_expand))+1))[:length]
对于python3:
def repeat_to_length(string_to_expand, length):
return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]
这篇关于将字符串重复到一定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文