lithuak
lithuak

Reputation: 6328

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

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

Answers (2)

Katriel
Katriel

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

FMc
FMc

Reputation: 42411

Nearly the same as Perl:

"0101" * N

Upvotes: 9

Related Questions