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
Pingback: Tweets that mention Python: Printing without newline or space :) | maSnun.com -- Topsy.com
In Py3K, use separator for printing without space. e.g.,
print(“Hello “, “World”, “!”, sep=”")
This will print Hello World!
@nasim
Yeah
Py3k is just cool… I have used it for a while back in my Windows days