What is the difference between print("\n") and print("\5")?
I tried below in a python shell.
Why does print("\5") output a new line:
>>> print("\n")
>>> print("\5")
>>>
But when I tried:
print("\4")
print("\6")
It's printing some binary data
Whenever you use print in python, it puts a newline at the end. The thing you should pay attention to is how many newlines are in the output.
"\5" is just a character (it's the control characters ENQ in ASCII; while it is technically non-printable, my terminal renders it as ♣); printing it outputs whatever your terminal decides to use to render it followed by a newline. print("") will output a newline. print("\n") by contrast will output two newlines.
If your terminal can't/won't render \5 (it is a non-printable character after all), print("\5") will be the same as print("").
Related
Carriage return or \r works as you have shifted your cursor to the beginning of the string or line. so, whenever you will use this special escape character \r, the rest of the content after the \r will come at the front of your line and will keep replacing your characters one by one until it takes all the contents left after the \r in that string. right???
However, with me it only prints what is after \r
so,
print("don't wish for it work \r for it")
print only "for it"
Try:
print("don't wish for it work \n for it")
If you run the print statment from terminal, the output will be
for itish for it work
If you run the exact statement from IDE (Pycharm), the output will be for it. This could be due to a bug/feature. In order to get the exact output in Pycharm IDE, go to Run > Edit Configuration > Emulate Terminal in output console and select this option. You will get the exact result as described in your statement.
for itish for it work
Other answers seem to be providing little explanation for what's the problem.
When you are running your code, two cases can happen:
\r starts to overwrite character from previous line (without clearing the entire line) which will give you following output:
print("don't wish for it work \r for it")
|don't wish for it work -- line 1
+| for it -- line 2
| for itish for it work -- line 1 overwritten by line 2 (only overlapping chars)
\r clears the previous line and writes content following \r, which will give you following output:
print("don't wish for it work \r for it")
|don't wish for it work -- line 1
+| for it -- line 2
| for it -- line 1 cleared. line 2 is output
Since behaviour of carriage return can vary from system to system, consider using \n as shown in #KJDII's answer or understand and configure the behaviour for which system you will run it on.
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'm writing a little python utility to help move our shell -help documentation to searchable webpages, but I hit a weird block :
output = subprocess.Popen([sys.argv[1], '--help'],stdout=subprocess.PIPE).communicate()[0]
output = output.split('\n')
print output[4]
#NAME
for l in output[4]:
print l
#N
#A
#
#A
#M
#
#M
#E
#
#E
#or when written, n?na?am?me?e
It does this for any heading/subheading in the documentation, which makes it near unusable.
Any tips on getting correct formatting? Where did I screw up?
Thanks
The documentation contains overstruck characters done in the ancient line-printer way: print each character, followed by a backspace (\b aka \x08), followed by the same character again. So "NAME" becomes "N\bNA\bAM\bME\bE". If you can convince the program not to output that way, it would be the best; otherwise, you can clean it up with something like output = re.sub(r'\x08.', '', output)
A common way to mark a character as bold in a terminal is to print the character, followed by a backspace characters, followed by the character itself again (just like you would do it on a mechanical typewriter). Terminal emulators like xterm detect such sequences and turn them into bold characters. Programs shouldn't be printing such sequences if stdout is not a terminal, but if your tool does, you will have to clean up the mess yourself.
I am printing a string to the python shell on a mac os 10.7.3.
The string contains new line characters, \n\r, and tabs, \t.
I'm not 100% sure what new line characters are used on each platform, however i've tried every combination (\n, \n\r, \r) and the newline characters are printed on the shell:
'hello\n\r\tworld'
I don't know what i'm doing wrong, any help is appreciated.
Thanks
What look to you like newlines and carriage returns are actually two characters each -- a back slash plus a normal character.
Fix this by using your_string.decode('string_escape'):
>>> s = 'hello\\n\\r\\tworld' # or s = r'hello\n\r\tworld'
>>> print s
hello\n\r\tworld
>>> print repr(s)
'hello\\n\\r\\tworld'
>>> print s.decode('string_escape')
hello
world
I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the newline after formatting with the variable. I suspect Python might be taking in the newline as input when I hit return.
How can I make it so that the input does not include any newlines so that I may compare it to other strings/characters? (e.g. something == 'a')
You are correct - a newline is included in inputted. To remove it, you can just call strip("\r\n") to remove the newline from the end:
print("Input is {0}, including the return".format(inputted.strip("\r\n")))
This won't cause any issues if inputted does not have a newline at the end, but will remove any that are there, so you can use this whether inputted is user input or not.
If you don't want any newlines in the text at all, you can use inputted.replace("\r\n", "") to remove all newlines.
Your problem is actually Eclipse. Assuming that you use PyDev, I was able to reproduce the problem. When entering something in the Eclipse console, the problem occurs as described in your question. But when directly executing the very same script with the Python 3.1.1 interpreter, inputted does not include a newline character.
I investigated the Python source code and found out input() uses GNU readline if stdin is interactive (i.e. a TTY or prompt, however you want to call it), but falls back to the .readline() method of the stdin object if necessary. Then, if the result of readline ends with \n, that character is removed. Note: No CR-LF or LF-CR handling here (in the fallback case)!
So I wrote this little script to see what actually happens:
import sys
from io import StringIO
for stdin in [sys.stdin, StringIO("test\r\ntest\r\n")]:
sys.stdin = stdin
print("readline returns this: " + repr(sys.stdin.readline()))
inputted = input("Enter in something: ")
print("inputted: " + repr(inputted))
print("inputted is printed like this: --> {0} <--".format(inputted))
It first executes the code with the normal stdin (console or Eclipse console) and then with a prepared stdin containing the text test\r\ntest\r\n.
Try and run the script in Eclipse - you must enter a string twice. The conclusion: Pressing Enter in the Eclipse console will produce CR-LF ("\r\n"). Printing "\r" in the Eclipse console will jump to the next line.
On the other side, running it in the Windows console will produce the expected output: input() returns a string without a newline at the end because (I guess) GNU readline is used. With the prepared stdin StringIO("test\r\n"), the input() result is "test\r" as in Eclipse (although not printed as newline).
Hope this all makes sense... but what I still don't know is if that is expected behavior of Eclipse.
If you only want to stript the last line endings, you could use rstrip.
inputted.rstrip ("\r\n")
inputted = inputted.strip()
Edit: As noted, this will kill all whitespace at the start and end. A way to get rid of only the trailing newline is:
import re
inputted = re.sub("[\n\r]+$", "", inputted)