[Tutor] Newline

ALAN GAULD alan.gauld at btinternet.com
Sat Dec 4 17:55:14 CET 2010



> >> ...      print(i, "spam", end="\n" if i==3 else "***")
> >
> > I hadn't thought of using the conditional expression there  but it
> > makes a lot of sense.

> So is this a  python3.x feature only? Is there an equivallent in 2.x? I

The end parameter of print is a Python 3 feature - only possible 
because print is now a function rather than a command.
In Python two the only option was to add a comma at the end 
of the print statement qwhich suppressed the newline.
But the end parameter allows you to add anything you like, 
not just newlines or a null.. Of course you can use string 
formatting in Python 2 to achieve similar results.

The if construct is nothing to do with print, it is a standard 
conditional expression introduced in Python v2.5 or 2.6? 
As is true of any *expression* it can be used anywhere 
that a value is used. This is because every expression 
produces to a value.

So in Python v2 we could simulate Steven's loop with:

for n in range(3):
    s += "%d spam%s" % (n,"\n" if n==3 else "***")
print s,  # comma to avoid print adding its own \n...

But the print(..., end=....) version is much prettier IMHO.

HTH,

Alan G.


More information about the Tutor mailing list