wonderwhy
wonderwhy

Reputation: 413

Python: Loop: formatting string

I don't know how to express this. I want to print:

_1__2__3__4_

With "_%s_" as a substring of that. How to get the main string when I format the substring? (as a shortcut of:

for x in range(1,5):
    print "_%s_" % (x)

(Even though this prints multiple lines))

Edit: just in one line

Upvotes: 2

Views: 4237

Answers (4)

semptic
semptic

Reputation: 654

Python 3:

print("_{}_".format("__".join(map(str,range(1,5)))))
_1__2__3__4_

Python 2:

print "_{0}_".format("__".join(map(str,range(1,5))))
_1__2__3__4_

Upvotes: 1

Paul Seeb
Paul Seeb

Reputation: 6146

Did you mean something like this?

 my_string = "".join(["_%d_" % i for i in xrange(1,5)])

That creates a list of the substrings as requested and then concatenates the items in the list using the empty string as separator (See str.join() documentation).

Alternatively you can add to a string though a loop with the += operator although it is much slower and less efficient:

s = ""
for x in range(1,5):
    s += "_%d_" % x
print s

Upvotes: 8

Jason Hu
Jason Hu

Reputation: 6333

you can maintain your style if you want to.

if you are using python 2.7:

from __future__ import print_function
for x in range(1,5):
    print("_%s_" % (x), sep = '', end = '')
print()

for python 3.x, import is not required.

python doc: https://docs.python.org/2.7/library/functions.html?highlight=print#print

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

print("_" + "__".join(map(str, xrange(1,5)))) +"_"
_1__2__3__4_




In [9]: timeit ("_" + "__".join(map(str,xrange(1,5)))) +"_"

1000000 loops, best of 3: 1.38 µs per loop


In [10]: timeit "".join(["_%d_" % i for i in xrange(1,5)])
100000 loops, best of 3: 3.19 µs per loop

Upvotes: 2

Related Questions