I have a piece of code that will take a string and repeat it such that the length of the string is x.
>>> import math
>>> def repeat(data, length):
return (data * int(math.ceil(float(length) / len(data))))[:length]
>>> repeat("Hello World", 22)
'Hello WorldHello World'
>>> repeat("Hello World", 20)
'Hello WorldHello Wor'
Is there any way to optimize it?
I need this operation to be fast, as it will be used a lot.
Note that this also needs to work with lists.
This might be marginally faster:
I say “might” because a LOT depends on the typical
stringandlength! With'Hello World'and61, I’ve timed this (on an old Mac laptop) at 1 microsecond vs 1.66 microseconds for yours; with'Hello World'*100and61*123, 2.08 microseconds vs 2.68 for yours. Just how fast are you requiring, on what length strings, and for what typical values oflength?Note
//is “divide by truncation” (just to ensure this works in Python 3 as well as Python 2;-) even though Stack Overflow is coloring things as if it was a comment mark (as in C++).