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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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 🙂
3 replies on “Python: Printing without newline or space :)”
[…] This post was mentioned on Twitter by Abu Ashraf Masnun, Telletto. Telletto said: maSnun says… Python: Printing without newline or space :): While coding in Python, I have seen .. http://bit.ly/sg8O […]
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 🙂