Printing without a new line is simple in Python 3. In order to print without newline in Python, you need to add an extra argument to your print function that will tell the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') print("It is a great day.")
To print multiple values or variables without the default single space character in between, use the print() function with the optional separator keyword argument sep and set it to the empty string '' .
Python print() built-in function is used to print the given content inside the command prompt. The default functionality of Python print is that it adds a newline character at the end.
In Python 3, use
print('h', end='')
to suppress the endline terminator, and
print('a', 'b', 'c', sep='')
to suppress the whitespace separator between items. See the documentation for print
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
You need to call sys.stdout.flush()
because otherwise it will hold the text in a buffer and you won't see it.
Greg is right-- you can use sys.stdout.write
Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then
lst = ['h', 'm']
print "".join(lst)
Or use a +
, i.e.:
>>> print 'me'+'no'+'likee'+'spacees'+'pls'
menolikeespaceespls
Just make sure all are concatenate-able objects.
Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "hello",; print "there"
hello there
>>> print "hello",; sys.stdout.softspace=False; print "there"
hellothere
But really, you should use sys.stdout.write
directly.
For completeness, one other way is to clear the softspace value after performing the write.
import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"
prints helloworld !
Using stdout.write() is probably more convenient for most cases though.
This may look stupid, but seems to be the simplest:
print 'h',
print '\bm'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With