In my code I am trying to print without a new line after the program exits and print again. I am printing with a comma after for example:
type_d=dict.fromkeys(totals,[0,0])
for keysl in type_d.keys():
print type_d[keysl][0] , ",", type_d[keysl][1] , ",",
print "HI" ,
But when the program exits and I call on another one there is a newline inputted after the last value in the file. How can I avoid this?
I believe that this is not documented, but it's intentional, and related to behavior that is documented.
If you look up print in the docs:
A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.)
And Python does keep track of whether the last thing written to sys.stdout was written by print (including by print >>sys.stdout) or not (unless sys.stdout is not an actual file object). (See PyFile_SoftSpace in the C API docs.) That's how it does (3) above.
And it's also what it uses to decide whether to print a newline when closing stdout.
So, if you don't want that newline at the end, you can just do the same workaround mentioned in (3) at the end of your program:
for i in range(10):
print i,
print 'Hi',
sys.stdout.write('')
Now, when you run it:
$ python hi.py && python hi.py
0 1 2 3 4 5 6 7 8 9 Hi0 1 2 3 4 5 6 7 8 9 Hi
If you want to see the source responsible:
The PRINT_ITEM bytecode handler in ceval is where the "soft space" flag gets set.
The code that checks and outputs a newline or not depending on the flag is Py_FlushLine (which is also used by many other parts of Python).
The code that calls that check is, I believe, handle_system_exit—but notice that the various different "Very High Level C API" functions for running Python code in the same file also do the same thing at the end.
You can try to use the code below, it will eliminate the new line:
import sys
sys.stdout.write("HI")
Related
In Jupyter Notebook, when running the following Python codes, the number from 2 to 9 is printed, one after one.
import time
for i in range(1,10):
time.sleep(1)
sys.stderr.write('\r %d' % i)
sys.stderr.flush()
Q1: Why is 1 not printed?
Q2: Why the numbers are printed one after one, I mean, when a larger number is printed, the immediate smaller number disappears (which is awesome)? Why sys.stderr.write('\r %d' % i) works in this way but sys.stderr.write('%d \r' % i) works in a "normal" way which displays all the numbers?
When running the exact above codes in Linux terminal. The output is different again:
13
23
33
43
53
63
73
83
93
If I change the line sys.stderr.write('\r %d' % i) to sys.stderr.write('%d \r' % i), the output becomes:
3
3
3
3
3
3
3
3
3
This is so strange.
Q3: Why running the above codes in Linux terminal has different output?
Q1: Why is 1 not printed?
It did print though. Try a longer sleep.
Q2: Why the numbers are printed one after one, I mean, when a larger number is printed, the immediate smaller number disappears (which is awesome)?
It's because you're using a carriage return \r instead of a linefeed \n, which returns the cursor to the start of the line, instead of advancing it to the next line. You can also overwrite things in the terminal using a backspace \b to move the cursor back one space.
Q3: Why running the above codes in Linux terminal has different output?
I'm not sure which terminal you mean. Some terminals don't support overwrite, so the order you flush can affect the output.
Also, look at the docstring on the write method,
write(s) method of idlelib.run.PseudoOutputFile instance
Write string to stream.
Returns the number of characters written (which is always equal to
the length of the string).
It returns the length of the string you passed in. In the Python shell (REPL), all return values get printed after the function returns. Try this in IDLE where stdin and stderr print in different colors:
>>> sys.stderr.write('x')
But look at what happens if you run this in a terminal,
>>> sys.stdout.write('abc\r')
4bc
First it prints abc then returns the cursor to the start of the line. Then it returns 4 because the string had len 4, so Python's REPL prints that at the cursor's current location, overwriting the a.
While teaching a friend python i came across a weird case involving issues with indentations.
Following is the piece of code which i was using
while 1:
a = raw_input("input: ")
if not a:
break
values = a.split()
print values
So the issue was the friend used tab to indent the first 4 lines i.e
while 1:
a = raw_input("Input: ")
if not a:
break
and then used spaces to indent the remaining code. i.e. following part
values = a.split()
print values
The piece of code did not throw the indentation error, which i guess is right because the tabs were defaulted to create 4 spaces.
Where it really got weird was that the unless the break condition was met, the part which used spaces was not getting executed.
i.e the output was as follows
Input
Input: 123 123 123
Input: abc abc abc
Input: pqr abc 123
Output
['pqr', 'abc', '123']
Expected Output
['123', '123', '123']
['abc', 'abc', 'abc']
['pqr', 'pqr', 'pqr']
Why could this be happening?
What am i missing about the battle of tabs and spaces in python interpreter
Python 2 has exactly one interpretation of tabs: They are equivalent to eight spaces, always (your IDE may show them as something else, but Python and your IDE aren't on speaking terms). Knowing that, your final statements are clearly outside the loop body.
Python 3 doesn't have this problem; if you mix tabs and spaces, it will raise a SyntaxError (refusing the temptation to guess, per The Zen of Python [import this]). I'd suggest configuring your editor to make literal tabs display differently (e.g. in vim, set listchars=tab:~>,trail:#, set list shows tabs and trailing space as characters), and of course, configure it to automatically expand newly inserted tabs (e.g. set expandtab), not just interpret them as four spaces (in fact, having them interpreted as eight spaces would give you a more accurate interpretation of how Python 2 will see it).
Alternatively, invoke the Python 2 interpreter with -t or -tt which makes mixed tabs and spaces warnings (-t) or errors (-tt), to make this sort of problem easier to stamp out.
Today, I'm learning the built-in function chr. And through ascii-table search, I found \x08 means backspace. So I played a bit with it. But the result confused me:
In [52]: print '1\x08'
1
In [53]: print '1\x082'
2
It seems that only follow by another character, \x08 will behave like a backspace, why does this happened? How \x08 behaves in a string?
It's behaving like a backspace in both cases, which is to say it moves your cursor back one space. It does not, however, delete what's there unless you write something else. So in the first case, the 1 remains, but in the second it is overwritten with a 2.
Backspace only moves the cursor by one character, it does not actually delete it. This for example results in 193:
print('123\x08\x089')
You can use space to actually "delete" the character...
1---- backspace simply move the cursor to the left one space, and
if you use the work or other editor it will also delete the left one character.
and what you must know is that backspace is also a character the same as 1 or a.
2---- the terminal as our default output device, you can also put him as a file.
So if you use
print '1\x08'
it means that you write a 1 and a backspace in the file stdout.
if you read the file, the system reads 1 + breakspace, you will get an 1.
and if you use
print '1\x082'
it means that you write a 1, a backspace and a 2 in the file stdout.
if you read the file, the system get 1 + breakspace + 2, when you print them, you will only get an 2, because it covers the first 1 when you use backspace.
for detail you can see the next test code
if __name__ == "__main__":
print "1\x08"
print "1\x082"
f = open("1.txt", "w")
f.write("1\x08\x082")
f.close();
f = open("1.txt", "r")
str = f.readlines( )
print len(str), str
for s in str:
print "s=|" + s + "|"
you can see the string s=|1\x08\x082| display s=2|. becasue the |1 not display when backspace two times.
first of all, I'm new to python, so maybe my code is a little weird or bordering to be wrong, but it works, so there is that.
I've been googleing for this problem, but can't find anyone who writes about, I got this huge list written like this
1 2 3 4 5
2 2 2 2 2
3 3 3 3 3
etc, note that it is spaces and not tab, and this I can't change, since I'm working with a print out from ls-dyna
So I am using this script to remove the whitespaces before the numbers, since they have been giving me troubles when trying to format the numbers into a matrix and then i remove the empty lines afterwards
for line in input:
print >> output, line.lstrip(' ')
but for some reason, I have 4442 lines (and here I mean writen lines, which is easy to track since they are enumerated) but the output only has 4411, so it removes 31 lines, with numbers I need
Why is this?
The lstrip() won't remove lines because it is used inside the print statement which will always append a newline character (the way you use it). But the for line in input might step through the list of lines in an unexpected way, i. e. it could skip lines or combine them in a manner you didn't expect.
Maybe newline and carriage return characters result in this strange problem.
I propose to let the .lstrip(' ') away for testing and compare the output with the input to find the places where something gets changed. Probably you should use output.write(line) to circumvent all the automatics of the print statement (especially appending newline characters).
Then you should use a special separator when outputting (output.write('###' + line) or similar) to find out how the iteration through the input takes place.
Given a string s containing (syntactically valid) Python source code, how can I split s into an array whose elements are the strings corresponding to the Python "statements" in s?
I put scare-quotes around "statements" because this term does not capture exactly what I'm looking for. Rather than trying to come up with a more accurate wording, here's an example. Compare the following two ipython interactions:
In [1]: if 1 > 0:
......: pass
......:
In [2]: if 1 > 0
File "<ipython-input-1082-0b411f095922>", line 1
if 1 > 0
^
SyntaxError: invalid syntax
In the first interaction, after the first [RETURN] statement, ipython processes the input if 1 > 0: without objection, even though it is still incomplete (i.e. it is not a full Python statement). In contrast, in the second interaction, the input is not only incomplete (in this sense), but also not acceptable to ipython.
As a second, more complete example, suppose the file foo.py contains the following Python source code:
def print_vertically(s):
'''A pretty useless procedure.
Prints the characters in its argument one per line.
'''
for c in s:
print c
greeting = ('hello '
'world'.
upper())
print_vertically(greeting)
Now, if I ran the following snippet, featuring the desired split_python_source function:
src = open('foo.py').read()
for i, s in enumerate(split_python_source(src)):
print '%d. >>>%s<<<' % (i, s)
the output would look like this:
0. >>>def print_vertically(s):<<<
1. >>> '''A pretty useless procedure.
Prints the characters in its argument one per line.
'''<<<
2. >>> for c in s:<<<
3. >>> print c<<<
4. >>>greeting = ('hello '
'world'.
upper())<<<
5. >>>print_vertically(greeting)<<<
As you can see, in this splitting, for c in s: (for example) gets assigned to its own item, rather being part of some "compound statement."
In fact, I don't have a very precise specification for how the splitting should be done, as long as it is done "at the joints" (like ipython does).
I'm not familiar with the internals of the Python lexer (though almost certainly many people on SO are :), but my guess is that you're basically looking for lines, with one important exception : paired open-close delimiters that can span multiple lines.
As a quick and dirty first pass, you might be able to start with something that splits a piece of code on newlines, and then you could merge successive lines that are found to contain paired delimiters -- parentheses (), braces {}, brackets [], and quotes '', ''' ''' are the ones that come to mind.