faqts : Computers : Programming : Languages : Python : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

20 of 23 people (87%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I print a string without a newline afterwards?

Jul 8th, 2002 12:49
Michael Chermside, BlackShift, unknown unknown,


If you use the print statement to print multiple lines of text, you will
find that it inserts a newline after each print statement:
>>> print 'Hello'
>>> print 'World!'
outputs:
    Hello
    World!
To avoid getting this extra newline (if you don't want it) you can add a
comma after the text you want to print:
>>> print 'Hello',
>>> print 'World!'
outputs:
   Hello World!
However, you will note that it DOES place a space between its arguments,
and there's no way (except fairly deep magic) to turn THAT off.
If you want FULL control of your output, then don't use the "print"
statement at all; go with the write() method on sys.stdout instead. 
>>> import sys
>>> sys.stdout.write( 'Hello' )
>>> sys.stdout.write( 'World!' )
>>> sys.stdout.write( '\n' )
outputs:
   HelloWorld!
Note: The stdout.write() approach is the one favored by nearly all
advanced Python programmers for any serious programming beyond one-off
scripts. But it's somewhat more verbose, so feel free to use print as
long as it will do what you want. Mixing print and stdout.write() is
possible, but sometimes on some platforms may not work as you expect...
sticking to one approach is preferred.