[Tutor] print command

nicke hiower4 at elitemail.org
Tue Mar 22 22:10:54 CET 2005


On Mon, 21 Mar 2005 05:57:28 -0500
Kent Johnson <kent37 at tds.net> wrote:

> 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
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

why make it difficult? ;)

print 1,
print '\b'+str(2),
print '\b'+str(3)

'\b' is the escape character for backspace.


More information about the Tutor mailing list