Python: how to print without white spaces?

Question:

I have following code:

for i in range(1,6):
    print 'Answer',i,':'

Output is:

Answer 1 :
Answer 2 :
Answer 3 :
Answer 4 :

I want it to be like this:

Answer 1:
Answer 2:
Answer 3:
Answer 4:

i.e. without spaces in between integer and ‘:’
How to do this?

Asked By: Ravi Ojha

||

Answers:

Use string formatting:

for i in range(1, 5):
    print 'Answer {0}:'.format(i)
Answered By: Jon Clements

Try using this:

for i in range(1,5):
    print "Answer %d:" % i
Answered By: arulmr

Alternative:

for i in range(1,6):
    print 'Answer '+str(i)+':'
Answered By: Thanakron Tandavas
for i in range(1, 5):
    print "Answer", str(i)+':'

When you are printing with ',', the space is added automatically, you can concatenate output by either using + or positioning strings next to each other (in Python 2.x), like so:

for i in range(1, 5):
    print 'Answer'+str(i), ':'
    print 'Answer%d'':'%i

Check the difference!

Answered By: catalesia
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.