[Tutor] print command
Kent Johnson
kent37 at tds.net
Mon Mar 21 11:57:28 CET 2005
Shitiz Bansal wrote:
> Now this is so basic, i am feeling sheepish asking
> about it.
> I am outputting to the terminal, how do i use a print
> command without making it jump no newline after
> execution, which is the default behaviour in python.
> To clarify:
>
> print 1
> print 2
> print 3
>
> I want output to be
>
> 123
You can suppress the newline by ending the print statement with a comma, but you will still get the
space:
print 1,
print 2,
print 3
will print
1 2 3
You can get full control of the output by using sys.stdout.write() instead of print. Note the
arguments to write() must be strings:
import sys
sys.stdout.write(str(1))
sys.stdout.write(str(2))
sys.stdout.write(str(3))
sys.stdout.write('\n')
Or you can accumulate the values into a list and print the list as Lutz has suggested:
l = []
l.append(1)
l.append(2)
l.append(3)
print ''.join(map(str, l))
where map(str, l) generates a list of strings by applying str() to each element of l:
>>> map(str, l)
['1', '2', '3']
and ''.join() takes the resulting list and concatenates it into a single string with individual
elements separated by the empty string ''.
Kent
More information about the Tutor
mailing list