This code is from http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions
with open("myfile.txt") as f:
for line in f:
print line,
What I don't understand is what's that , for at the end of print command.
I also checked doc, http://docs.python.org/2/library/functions.html#print.
Not understanding enough, is it a mistake?(it seems not. it's from the official tutorial).
I am from ruby/javascript and it's unusual for me.
In python 2.7, the comma is to show that the string will be printed on the same line
For example:
for i in xrange(10):
print i,
This will print
1 2 3 4 5 6 7 8 9
To do this in python 3 you would do this:
for i in xrange(10):
print(i,end=" ")
You will probably find this answer helpful
Printing horizontally in python
---- Edit ---
The documentation, http://docs.python.org/2/reference/simple_stmts.html#the-print-statement, says
A '\n' character is written at the end, unless the print statement ends with a comma.
It prevents the print from ending with a newline, allowing you to append a new print to the end of the line.
Python 3 changes this completely and the trailing comma is no longer accepted. You use the end parameter to change the line ending, setting it to a blank string to get the same effect.
From Python trailing comma after print executes next instruction:
In Python 2.x, a trailing , in a print statement prevents a new line to be emitted.
The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.
in python 2.7:
print line,
in python 3.x:
print(line, end = ' ')
Related
I have a bit of code from a class which prints a line, and every line is followed by an empty line.
Is there a way to adjust the following code so that I don't have to have those empty lines?
def bfield(self):
self.n=0
for i in self.whole:
for j in i:
print("{:>4}".format(j), end='')
self.n=self.n+1
if self.n==len(i):
print('\n')
self.n=0
I'll agree with Rahul Chowdhury, remove the \n. Pythons print command, by default, will always start a new line after each print call. Hence your addition of '\n' will always result in an empty line.
If you wanted to look into how to get around the whole newline thing python does (every call in its own line), I found this link for you. It is fairly simple to do!
EDIT: It just occurred to me I should maybe list a few of the options just in case the link goes down. Here is one example:
print("Hello ", end = '')
print("World!")
With this, you overwrite the usual python lineend with your end = '' argument.
Another option would be to use the sys library
import sys
and then call the stdout.write() function, like so:
sys.stdout.write("Hello ")
sys.stdout.write("World!")
I tried running the following program:
for i in range(5):
print(i, end=' ')
However, it waits for me to write some string in the next line and gives the output like:
0 1 2 3 4 'Hi'
where 'Hi' is what I input. I'm using the latest version 3.6.5 and can't seem to understand the reason behind this error. Can anyone help?
The default value for end is '\n', meaning that print() will write a newline character after printing the arguments. This would put the cursor on the next line.
Usually, stdout (to which print() writes by default) is also line buffered, meaning that data written to it is not flushed (and shown on your terminal) until a newline character is seen, to signal the end of the line.
You replaced the newline with a space, so no newline is written; instead a space is written, letting you write successive numbers one after the other on the same line.
Add an extra, empty print() call after your for loop to write the newline after looping:
for i in range(5):
print(i, end=' ')
print()
You could also add flush=True to the print(..., end=' ') calls to explicitly flush the buffer.
Alternatively, for a small enough range(), pass in the values to print() as separate arguments, leaving end at the default. Separate arguments are separated by the sep argument, by default set to a space:
print(*range(5))
The * in front of the range() object tells Python to loop over the range() object and pass all values that produces as separate arguments to the print() call; so all 5 numbers are printed with spaces in between and a newline character at the end:
>>> print(*range(5))
0 1 2 3 4
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 7 years ago.
I am a new to python programming. I've followed the "Learn python the hard way" book but that is based on python 2x.
def print_one_line(line_number,f):
print(line_number,f.readline())
In this function every time it prints A line and a new line.
1 gdfgty
2 yrty
3 l
I read the documentary that if i put a , (comma) after readline()
then it won't print a new \n.
Here is the documentary:
Why are there empty lines between the lines in the file? The
readline() function returns the \n that's in the file at the end of
that line. This means that print's \n is being added to the one
already returned by readline() fuction. To change this behavior simply add a ,
(comma) at the end of print so that it doesn't print its own .
When I run the file with python 2x then it is OK, but when I do it in python 3x then the newline is printed. How to avoid that newline in python 3x?
Since your content already contains the newlines you want, tell the print() function not to add any by using the optional end argument:
def print_one_line(line_number,f):
print(line_number,f.readline(), end='')
Beside the other ways, you could also use:
import sys
sys.stdout.write(f.readline())
Works with every Python version to date.
Rather than skipping the newline on output, you can strip it from the input:
print(line_number, f.readline().rstrip('\n'))
I am unable to print the output on a single line without printing new lines, the following code shows syntax error:
print( "tiers found:"+eval("str.lower(tier.attrib['TIER_ID'])"), end=', ')
^
SyntaxError: invalid syntax
But this works fine:
print( "tiers found:"+eval("str.lower(tier.attrib['TIER_ID'])"))
the print statement is in a for loop and I require to print the output as comma separated list.
So whats the problem here?
Why are you using eval on a completely sane statement?
from __future__ import print_function
print('tiers found: {0}'.format(tier.attrib['TIER_ID'].lower()), end=',')
One cause could be that the first piece of code is executed with Python 2 and the second one with Python 3.
If that's not it, then try end=", ". My guess is that the second single quote isn't actually the quote that you want (i.e. it's backtick instead of single quote or something like that).
Or maybe there is an illegal character in there that you can't see in your editor.
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 9 years ago.
When I use the print command, it prints whatever I want and then goes to a different line. For example:
print "this should be"; print "on the same line"
Should return:
this should be on the same line
but instead returns:
this should be
on the same line
More precisely I was trying to create a program with if that told me whether a number was a 2 or not
def test2(x):
if x == 2:
print "Yeah bro, that's tottaly a two"
else:
print "Nope, that is not a two. That is a (x)"
But it doesn't recognise the last (x) as the value entered, and rather prints exactly: "(x)" (the letter with the brackets). To make it work I have to write:
print "Nope, that is not a two. That is a"; print (x)
And if e.g. I enter test2(3) that gives:
Nope, that is not a two, that is a
3
So either I need to make Python recognise my (x) inside a print line as the number; or to print two separate things but on the same line.
IMPORTANT NOTE: I am using version 2.5.4
Another note: If I put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.
In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:
print("Nope, that is not a two. That is a", end="")
In Python 2.x, you can use a trailing comma:
print "this should be",
print "on the same line"
You don't need this to simply print a variable, though:
print "Nope, that is not a two. That is a", x
Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use
from __future__ import print_function
to get access to the Python 3 print function or use sys.stdout.write().
In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
yields:
hi thereBob here.
Note that there is no newline or blank space between the two strings.
In Python 3.x, with its print() function, you can just say
print('this is a string', end="")
print(' and this is on the same line')
and get:
this is a string and this is on the same line
There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)
E.g.,
Python 2.x
print 'hi', 'there'
gives
hi there
Python 3.x
print('hi', 'there', sep='')
gives
hithere
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
You simply need to do:
print 'lakjdfljsdf', # trailing comma
However in:
print 'lkajdlfjasd', 'ljkadfljasf'
There is implicit whitespace (ie ' ').
You also have the option of:
import sys
sys.stdout.write('some data here without a new line')
Utilize a trailing comma to prevent a new line from being presented:
print "this should be"; print "on the same line"
Should be:
print "this should be", "on the same line"
In addition, you can just attach the variable being passed to the end of the desired string by:
print "Nope, that is not a two. That is a", x
You can also use:
print "Nope, that is not a two. That is a %d" % x #assuming x is always an int
You can access additional documentation regarding string formatting utilizing the % operator (modulo).