也許不是最有效的解決方案,但可以肯定的短&簡單:
def repstr(string, length):
return (string * length)[0:length]
repstr("foobar", 14)
給出 「foobarfoobarfo」。有關這個版本的一點是,如果長度爲< len(string),那麼輸出字符串將被截斷。例如:
repstr("foobar", 3)
給出「foo」。
編輯:其實讓我驚訝,這比目前公認的解決方案(以下簡稱「repeat_to_length」功能),至少在短字符串更快:
from timeit import Timer
t1 = Timer("repstr('foofoo', 30)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo', 30)", 'from __main__ import repeat_to_length')
t1.timeit() # gives ~0.35 secs
t2.timeit() # gives ~0.43 secs
據推測,如果字符串很長,或長度爲非常高(即如果string * length
部分的浪費高),那麼它表現不佳。而事實上,我們可以修改上面的驗證這一點:
from timeit import Timer
t1 = Timer("repstr('foofoo' * 10, 3000)", 'from __main__ import repstr')
t2 = Timer("repeat_to_length('foofoo' * 10, 3000)", 'from __main__ import repeat_to_length')
t1.timeit() # gives ~18.85 secs
t2.timeit() # gives ~1.13 secs
看起來這是利用整數師。在Python 3中,這不需要'//'嗎?或者刪除'+ 1'並使用明確的呼叫到天花板功能就足夠了。另外,請注意:生成的字符串實際上在均勻分割時會有額外的重複;多餘的部分被拼接切斷。起初讓我困惑。 – jpmc26 2013-05-03 22:49:20
'int()'在這裏做同樣的事情,但是,'// //'可能在微觀上更快,因爲它在一個命令而不是兩個命令中執行了分隔和底線。 – Doyousketch2 2018-01-15 14:35:08