Python: Printing without newline or space :)

While coding in Python, I have seen that the Print statement adds a newline to it’s output which is very helpful in most cases. While I have to add a newline character manually in PHP, I have to type less in Python. I used to love this feature until I faced a situation when I have to print out data without any newline character or space. I finally found out the solution :) I have to write the characters of a string manually to stdout using the “sys” module.

Have a look at the following codes:

import sys
 
def masnun_print(string):
	for c in str(string):
		sys.stdout.write(c)
 
 
masnun_print("Hello world!")
 
masnun_print("\n")
 
for x in range(100):
	masnun_print(x)
 
masnun_print("\n")

As you can see, I have defined a function masnun_print() that prints out it’s default argument without space just like the echo statement in PHP. To give a line break between the “Hello World!” and the “1 to 100 series”, we have manually printed out newline character :)

This entry was posted in Blog Post and tagged . Bookmark the permalink.

3 Responses to Python: Printing without newline or space :)

  1. Pingback: Tweets that mention Python: Printing without newline or space :) | maSnun.com -- Topsy.com

  2. nasim says:

    In Py3K, use separator for printing without space. e.g.,

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

    This will print Hello World!

  3. maSnun says:

    @nasim
    Yeah :D
    Py3k is just cool… I have used it for a while back in my Windows days :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">