In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
print adds a newline by default. To avoid this, use a trailing ,:
print "Line 1 is",
print "big"
The , will still yield a space. To avoid the space as well, either concatenate your strings and use a single print statement, or use sys.stdout.write() instead.
From the documentation:
A '\n' character is written at the
end, unless the print statement ends
with a comma. This is the only action
if the statement contains just the
keyword print.
If you need full control of the bytes written to the output, you might want to use sys.stdout
import sys
sys.stdout.write("Line 1 is ")
sys.stdout.write("big!\n")
When not outputing a newline (\n) you will need to explicitly call flush, for your data to not be buffered, like so:
sys.stdout.flush()
this is standard functionality, use print "foo",
Related
I am following a beginners tutorial on Python, there is a small exercise where I have to add an extra function call and print a line between verses, this works fine if I print an empty line in between function calls but if I add an empty print line to the end of my happyBirthday() I get an indent error, without the added print line all works fine though, any suggestions as to why?
Here is the code:
def happyBirthday(person):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear " + person + ".")
print("Happy Birthday to you!")
print("\n") #error line
happyBirthday('Emily')
happyBirthday('Andre')
happyBirthday('Maria')
You can just do
print()
to get an empty line.
You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).
Trust in the error message -- if it says something specific, assume it to be true and figure out why.
Python 2.x:
Prints a newline
print
Python 3.x:
You must call the function
print()
Source: https://docs.python.org/3.0/whatsnew/3.0.html
Don't do
print("\n")
on the last line. It will give you 2 empty lines.
Python's print function adds a newline character to its input. If you give it no input it will just print a newline character
print()
Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text
my_str = "hello world"
print(my_str + "\n")
If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")
print("hello world", end="\n\n")
But you probably don't need this last method, the two before are much clearer.
The two common to print a blank line in Python-
The old school way:
print "hello\n"
Writing the word print alone would do that:
print "hello"
print
This is are other ways of printing empty lines in python
# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n")
print("\n") #prints 2 empty lines
print() #prints 1 empty line
It appears that Python's io.StringIO adds an extra newline at the end when I'm calling its getvalue method.
For the following code:
import io
s = io.StringIO()
s.write("1\n2\n3\n4\n5\n")
res = s.getvalue()
s.close()
print(res)
What I'm getting is this, with an extra newline in the end:
1
2
3
4
5
I checked the output with a hex editor, and I'm sure there's an extra newline.
The document says that:
The newline argument works like that of TextIOWrapper. The default is to consider only \n characters as ends of lines and to do no newline translation. If newline is set to None, newlines are written as \n on all platforms, but universal newline decoding is still performed when reading.
And I don't recall the write method append newlines per call.
So why is it adding newlines? I'm writing a script so I would like to make sure that it's behavior is consistent.
StringIO isn't doing this, it's print.
print prints all its arguments, seperated by sep (by default a space), and ending with end, by default a newline. You can suppress that by doing:
print(res, end="")
In the following code:
with open("output", "w") as f:
print >> f, "foo"
print >> f, "bar"
The 'output' file will be:
foo
bar
How to avoid newline and white spaces using print >>?
P.S.: I'm actually wanting to know if it is possible to do it using print >>. I know other ways in which I can avoid the '\n', such as f.write("foo") and f.write("bar").
Also, I know about the trailing comma. But that prints foo bar, instead of foobar.
A trailing comma makes the print statement do magic, like printing no newline unless there’s no further output (not documented!):
print >>f, "foo",
but that’s not really helpful if you want a consistent no-newline policy (and because you have a second print, which will print a space). For that, use Python 3’s print function:
from __future__ import print_function
and
print("foo", end="", file=f)
I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)
If a trailing comma is added to the end of a print statement, the next statement is executed first. Why is this? For example, this executes 10000 ** 10000 before it prints "Hi ":
print "Hi",
print 10000 ** 10000
And this takes a while before printing "Hi Hello":
def sayHello():
for i in [0] * 100000000: pass
print "Hello"
print "Hi",
sayHello()
In Python 2.x, a trailing , in a print statement prevents a new line to be emitted.
In Python 3.x, use print("Hi", end="") to achieve the same effect.
The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.
You're seeing the effects of stdout buffering: Disable output buffering
As others mention, standard out is buffered. You can try using this at points that you need the output to appear:
sys.stdout.flush()
print automatically puts a newline at the end of a string. This isn’t necessarily what we want; for example, we might want to print several pieces of data separately and have them all appear on one line. To prevent the newline from being added, put a comma at the end of the print statement:
d=6
print d,
print d
Output:
6 6