What is the right "pythonic" wa开发者_高级运维y 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
Nearly the same as Perl:
"0101" * N
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.
精彩评论