Print without a new line or space in Python

Here is another little trick in Python; the print statement always inserts a line break after it prints your text, for example:

print "Hello"
print "Python"
print "!"

Will print:
Hello
Python
!

Now, you can fix the issue with the line break by inserting a comma after the print statement:

print "Hello",
print "Python",
print "!"

This will print:
Hello Python !

But the problem is that it will still insert a space after it prints the text, so to fix this you will have to use sys.stdout.write like this:

import sys
sys.stdout.write("Hello ")
sys.stdout.write("Python")
sys.stdout.write("!")

This will print:
Hello Python!

Have fun with Python :)

4 Comments for Print without a new line or space in Python

  1. Jake Wharton said,

    November 6, 2008 @ 3:58 pm

    For Python 3.0 the print statement is now a function.

    print “Hello!” is now print(”Hello!”)

    Your space-less example would be obtained by using the sep paramater.

    print(”Hello “, “Python”, “!”, sep=”")

  2. Codehead said,

    November 6, 2008 @ 4:11 pm

    Jake, that’s good to know, thanks!
    I didn’t have time to look at Python 3.0 yet.

  3. nick said,

    December 16, 2008 @ 7:24 pm

    in Python 5, the print statement can be used as a statement, or a function. It doesnt matter.

  4. Codehead said,

    December 16, 2008 @ 7:41 pm

    Python 5?!

RSS comments feed· TrackBack URI Print without a new line or space in Python

Leave a Comment for Print without a new line or space in Python