开发者

Python: right way to build a string by joining a smaller substring N times

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜