Print output not showing the correct format - python

I have written the python code as below:
magicNumber = 25
for n in range(100):
if n is magicNumber:
print(n, " is the magic number")
break
else:
print(n)
The last line of output is showing in the format as below:
(25, ' is the magic number')
Please let me know what can i do to have the last line of the output as:
25 is the magic number

There's many ways you can accomplish this, since you're using python 2, there isn't a default print function. So you will have to import it, one way will be to add this on the top of your code.
from __future__ import print_function
Other ways include using string formatting such as:
print "%s is the magic number" % n
And
print "{0} is the magic number".format(n)
Or you can just easily remove the brackets and it will all be the same.
print n, "is the magic number"

You're running the code in python 2. That explains the braces being printed. Run in python 3 it'll work as you expect. Or if you still prefer python 2,then just remove the braces and put
print n,' is the magicnumber'

for python 2.x - print acts as a command
just remove the brackets and it will work as expected.
print n, " is the magic number"
for python 3.x - print acts as a function; so below is fine.
print(n, " is the magic number")
There are some other methods also as suggested by the user abccd.

Related

Python 3 to Python 2.6 using Pycharm, "end=" syntax error [duplicate]

I have this python script where I need to run gdal_retile.py,
but I get an exception on this line:
if Verbose:
print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')
The end=' ' is invalid syntax. I am curious as to why, and what the author probably meant to do.
I'm new to python if you haven't already guessed.
I think the root cause of the problem is that these imports are failing
and therefore one must contain this import from __future__ import print_function
try:
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
from osgeo.gdalconst import *
except:
import gdal
import ogr
import osr
from gdalconst import *
Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because print is still a statement.
print("foo" % bar, end=" ")
in Python 2.x is identical to
print ("foo" % bar, end=" ")
or
print "foo" % bar, end=" "
i.e. as a call to print with a tuple as argument.
That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x print is an actual function, so it takes keyword arguments, too.
The correct idiom in Python 2.x for end=" " is:
print "foo" % bar,
(note the final comma, this makes it end the line with a space rather than a linebreak)
If you want more control over the output, consider using sys.stdout directly. This won't do any special magic with the output.
Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the __future__ module to enable it in your script file:
from __future__ import print_function
The same goes with unicode_literals and some other nice things (with_statement, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.
How about this:
#Only for use in Python 2.6.0a2 and later
from __future__ import print_function
This allows you to use the Python 3.0 style print function without having to hand-edit all occurrences of print :)
In python 2.7 here is how you do it
mantra = 'Always look on the bright side of life'
for c in mantra: print c,
#output
A l w a y s l o o k o n t h e b r i g h t s i d e o f l i f e
In python 3.x
myjob= 'hacker'
for c in myjob: print (c, end=' ')
#output
h a c k e r
First of all, you're missing a quote at the beginning but this is probably a copy/paste error.
In Python 3.x, the end=' ' part will place a space after the displayed string instead of a newline. To do the same thing in Python 2.x, you'd put a comma at the end:
print "Building internam Index for %d tile(s) ..." % len(inputTiles),
I think he's using Python 3.0 and you're using Python 2.6.
This is just a version thing. Since Python 3.x the print is actually a function, so it now takes arguments like any normal function.
The end=' ' is just to say that you want a space after the end of the statement instead of a new line character. In Python 2.x you would have to do this by placing a comma at the end of the print statement.
For example, when in a Python 3.x environment:
while i<5:
print(i)
i=i+1
Will give the following output:
0
1
2
3
4
Where as:
while i<5:
print(i, end = ' ')
i=i+1
Will give as output:
0 1 2 3 4
It looks like you're just missing an opening double-quote. Try:
if Verbose:
print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')
Compatible with both Python 2 & 3:
sys.stdout.write('mytext')
Compatible with only Python 2
print 'mytext',
Compatible with only Python 3
print('mytext', end='')
I think the author probably meant:
if Verbose:
print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')
He's missing an initial quote after print(.
Note that as of Python 3.0, print is a function as opposed to a statement, if you're using older versions of Python the equivalent would be:
print "Building internam Index for %d tile(s) ..." % len(inputTiles)
The end parameter means that the line gets ' ' at the end rather than a newline character. The equivalent in earlier versions of Python is:
print "Building internam Index for %d tile(s) ..." % len(inputTiles),
(thanks Ignacio).
USE :: python3 filename.py
I had such error , this occured because i have two versions of python installed on my drive namely python2.7 and python3 .
Following was my code :
#!usr/bin/python
f = open('lines.txt')
for line in f.readlines():
print(line,end ='')
when i run it by the command python lines.py I got the following error
#!usr/bin/python
f = open('lines.txt')
for line in f.readlines():
print(line,end ='')
when I run it by the command python3 lines.py I executed successfully
For python 2.7 I had the same issue
Just use "from __future__ import print_function" without quotes to resolve this issue.This Ensures Python 2.6 and later Python 2.x can use Python 3.x print function.
Try this one if you are working with python 2.7:
from __future__ import print_function
Basically, it occurs in python2.7
here is my code of how it works:
i=5
while(i):
print i,
i=i-1
Output:
5 4 3 2 1
I had faced this error, and occurred because of using version 2.7.15 but end='' works with version 3 only.
Example:
import array as arr
a=arr.array('i',[1,2,3,4])
for x in range(0,3):
print ("%d" % a[x], end=' ')
Output : Showing error "Invalid Syntax" as using version 2.7
For Version 2.7.15
use this syntax
import array as arr
a=arr.array('i',[1,2,3,4])
for x in range(0,3):
print ("%d" % a[x]),
Output : 1 2 3
Even I was getting that same error today. And I've experienced an interesting thing.
If you're using python 3.x and still getting the error, it might be a reason:
You have multiple python versions installed on same drive. And when
you're presing the f5 button the python shell window (of ver. < 3.x)
pops up
I was getting same error today, and noticed that thing. Trust me, when I execute my code from proper shell window (of ver. 3.x), I got satisfactory results
we need to import a header before using end='', as it is not included in the python's normal runtime.
from __future__ import print_function
it shall work perfectly now
Just for my own future reference (I've come here twice already at different times), If you check and you're definitely on a python 3.x or later and you're getting the error telling you the 'end=' syntax is incorrect:
Make sure that you're actually running the python script and not just trying to execute the file. I have done this in the heat of a moment and thought something was terribly wrong only to discover I was doing just that.
python "scriptName.py"
or
python3 "scriptName.py"

Replace ends of string in eclipse

I am trying to refactor a large source base in a company I work in. Instead of using the print function in python 2.7x I want to use the logger function.
for example:
print "Sample print %d" % timestamp
With logger.info("Sample print %d" % timestamp)
so basically, I want to remove the print , and insert what remains into parentheses and logger.info (Ill assume all current prints are INFO until a full refactor is possible).
Thanks in advance
Search for (^\s+)print (.*)$
Replace with $1logger.info($2)
Python should complain pretty fast about all the places where a print goes over more than a single line. You'll have to fix those places manually.
Note: This skips comments
The alternative is to look into the source for 2to3.py which replaces print ... with print(...) to convert code from Python 2 to 3.

How to count the number of user input at stdin in python

Hi I apologize if this looks like homework, but I have been trying and failing to make this work, and I would really appreciate some expert help. I am trying to self-teach myself python.
I'm trying to solve problems in CodinGame and the very first one expects you to count the times input strings are passed to the program. The input string comes in two parts (eg. "Sina dumb"). I tried to use this:
count = int(sys.stdin.readline())
count = int(input())
count = int(raw_input()) #python2
But the program fails with:
ValueError: invalid literal for int() with base 10: 'Sina dumb\n'
depending on if I leave the newline in or not.
Please what am I doing wrong, and how can I make it better?
In python2.x or python 3.x
sys.stdin.readline() and input gives type str. So int("string") will produce error if string contains chars.
I think you need this(assuming)
import sys
input_var = input() # or raw_input() for python 2.x
# entering Sina dumb
>>>print(len(input_var.split()))
2
Update
If you want to count how much input you enter.Try this
import sys
from itertools import count
c = count(1)
while True:
input_var = input()
print ("you entered " + str(next(c)) + " inputs")
On one hand, in this case, python say you that you tried ton convert the String 'Sina dumb\n into integer that is not valid, and this is true. This probably triggered at the second line, int(input)
On the other hand, to solve your problem,one simple approach as each row you pass as input contains the end of line character \n you can for example get the input content, and split it at \n characters and count the size of the resulting list.
input() in python 3.x and raw_input()in python 2.x give a string. If a string contains anything but numbers it will give a ValueError.
you could try regular expression:
import re
line = input()
count = len(re.findall(r'\w+', line))
print (count)

Python: avoid new line with print command [duplicate]

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).

Output without new line [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed last month.
how can I output text to the console without new line at the end?
for example:
print 'temp1'
print 'temp2'
output:
temp1
temp2
And I need:
temp1temp2
Add a comma after the last argument:
print 'temp1',
print 'temp2'
Alternatively, Call sys.stdout.write:
import sys
sys.stdout.write("Some output")
In Python > 2.6 and Python 3:
from __future__ import print_function
print('temp1', end='')
print('temp2', end='')
Try this:
print 'temp1',
print 'temp2'
There are multiple ways, but the usual choice is to use sys.stdout.write(), which -- unlike print -- prints exactly what you want. In Python 3.x (or in Python 2.6 with from __future__ import print_function) you can also use print(s, end='', sep=''), but at that point sys.stdout.write() is probably easier.
Another way would be to build a single string and print that:
>>> print "%s%s" % ('temp1', 'temp2')
But that obviously requires you to wait with writing until you know both strings, which is not always desirable, and it means having the entire string in memory (which, for big strings, may be an issue.)
for i in range(4):
print(a[i], end =" ")
Try
print 'temp1',
print '\btemp2'

Categories