I was solving a Python question on CodingBat.com. I wrote following code for a simple problem of printing a string n times-
def string_times(str, n):
return n * str
Official result is –
def string_times(str, n):
result = ""
for i in range(n):
result = result + str
return result
print string_times('hello',3)
The output is same for both the functions. I am curious how string multiplication (first function) perform against for loop (second function) on performance basis. I mean which one is faster and mostly used?
Also please suggest me a way to get the answer to this question myself (using time.clock() or something like that)
We can use the
timeitmodule to test this:You can see that multiplying is the far faster option. You can take note that while the string concatenation version isn’t that bad in CPython, that may not be true in other versions of Python. You should always opt for string multiplication or
str.join()for this reason – not only but speed, but for readability and conciseness.