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.
Related
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. :)
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!")
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 = ' ')
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).
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 26 days ago.
if len(trashed_files) == 0 :
print "No files trashed from current dir ('%s')" % os.path.realpath(os.curdir)
else :
index=raw_input("What file to restore [0..%d]: " % (len(trashed_files)-1))
if index == "*" :
for tfile in trashed_files :
try:
tfile.restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
elif index == "" :
print "Exiting"
else :
index = int(index)
try:
trashed_files[index].restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
I am getting:
elif index == "" :
^
IndentationError: expected an indented block
As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.
There are in fact multiples things you need to know about indentation in Python:
Python really cares about indention.
In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.
This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.
There are different indention errors and you reading them helps a lot:
1. "IndentationError: expected an indented block"
They are two main reasons why you could have such an error:
- You have a ":" without an indented block behind.
Here are two examples:
Example 1, no indented block:
Input:
if 3 != 4:
print("usual")
else:
Output:
File "<stdin>", line 4
^
IndentationError: expected an indented block
The output states that you need to have an indented block on line 4, after the else: statement
Example 2, unindented block:
Input:
if 3 != 4:
print("usual")
Output
File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
The output states that you need to have an indented block line 2, after the if 3 != 4: statement
- You are using Python2.x and have a mix of tabs and spaces:
Input
def foo():
if 1:
print 1
Please note that before if, there is a tab, and before print there is 8 spaces.
Output:
File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.
You can get some info here.
Remove all tabs and replaces them by four spaces.
And configure your editor to do that automatically.
2. "IndentationError: unexpected indent"
It is important to indent blocks, but only blocks that should be indent.
So basically this error says:
- You have an indented block without a ":" before it.
Example:
Input:
a = 3
a += 3
Output:
File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
The output states that he wasn't expecting an indent block line 2, then you should remove it.
3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)
You can get some info here.
But basically it's, you are using tabs and spaces in your code.
You don't want that.
Remove all tabs and replaces them by four spaces.
And configure your editor to do that automatically.
Eventually, to come back on your problem:
Just look at the line number of the error, and fix it using the previous information.
I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.
Specifically --- bad code that generates indentation errors:
def my_function(args):
"Here is my docstring"
....
Good code that avoids indentation errors:
def my_function(args):
"Here is my docstring"
....
Note: I'm not saying this is the problem, but that it might be, because in my case, it was!
You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
This is just an indentation problem since Python is very strict when it comes to it.
If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.