Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   print problem (http://www.programmingforums.org/showthread.php?t=11407)

MR.T Sep 26th, 2006 9:48 PM

print problem
 
When I print something in python with a for loop it automatically skips a line after each print, like this:

0
1
2
3
4
5

How do I keep it from skipping a line so it outputs like this: 012345?

thanks

DaWei Sep 26th, 2006 9:53 PM

Investigate the comma. That may still not suit you, so look into formatted printing. There is a ton of information on it in the Python docs. You could, of course, simply concatenate prior to the print.

Arevos Sep 27th, 2006 7:25 AM

As DaWei says, you can use a trailing comma:
:

  1. for i in range(6):
  2.     print i,
  3. print
  4. # prints: 0 1 2 3 4 5

Although this has the disadvantage of placing a space between each number. Or you could concatenate the numbers together:
:

  1. output = ""
  2. for i in range(6):
  3.     output += str(i)
  4. print output
  5. # prints: 012345

Or you could use a list comprehension:
:

  1. print "".join(str(i) for i in range(6))
  2. # prints 012345

Or you could use sys.stdout.write():
:

  1. import sys
  2. for i in range(6):
  3.     sys.stdout.write(str(i))
  4. sys.stdout.write("\n")
  5. # prints 012345


MR.T Sep 27th, 2006 2:56 PM

Ok, thanks for the help. I fixed my problem using the second method Arevos sugested.

peace_of_mind Sep 27th, 2006 3:39 PM

In the future posting the code you're having trouble with will help you get more helpful posts much quicker. Glad you got it sorted out, though.

Dietrich Sep 28th, 2006 6:46 PM

Just to be correct, our esteemed Arevos' list comprehension is really a generator expression.

free-zombie Oct 9th, 2006 6:01 PM

... and generator expressions are new in python2.4
luckily, python2.4 will enter debian stable soon (if etch is on time), which removes my last excuse to stick with python2.3 ;)

titaniumdecoy Oct 9th, 2006 7:00 PM

Are you kidding? The current version of Python is 2.5, you know.

Dietrich Oct 11th, 2006 4:16 PM

Quote:

Originally Posted by titaniumdecoy (Post 116143)
Are you kidding? The current version of Python is 2.5, you know.

Unless your customer uses Python 2.3

hydroxide Oct 23rd, 2006 1:30 PM

Quote:

Originally Posted by Dietrich (Post 116259)
Unless your customer uses Python 2.3

Heh! I've been pushing to get rid of 2.2 support from a certain project for a while -- the idioms 2.3 adds are so much nicer. Ah well... 2.5 will go stable sometime... as will 2.6... as will 2.7...

yrs obsolescent-compatibility-hurts-my-eyes-ly, -T.


All times are GMT -5. The time now is 1:09 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC