Reputation: 6328
What is the right "pythonic" way to do the following operation?
s = ""
for i in xrange(0, N):
s += "0101"
E.g. in Perl it would be: $s = "0101" x $N
Upvotes: 0
Views: 149
Reputation: 123622
The most Pythonic way would be
s = "0101" * N
Other methods include:
use StringIO
, which is a file-like object for building strings:
from StringIO import StringIO
use "".join
; that is
`"".join("0101" for i in xrange(N)`
use your algorithm. In an unoptimised world this is less good, because it is quadratic in the length of the string. I believe recent versions of Python actually optimise this so that it is linear, but I can't find a reference for that.
Upvotes: 2