Prevent python from printing newline - python

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)

Related

Why print("\5") output a new line in python

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

how to change the position of the cursor in python 3

I am on windows 10 and I prefer not to install a new module (standard library solutions are accepted). I want the text that the user enters to start at the end of the third line.
My code:
print(" Enter password to unlock the Safe .\n\n password : \n\n\t2 attempts remaining .")
# code to move the cursor to the end of " password : " goes here
x = input()
output:
wanted output:
Also ANSI escape sequences don't seem to work without colorama(which unfortunately is an external module).
On Windows 10 you can use ANSI escape sequences as found in Console Virtual Terminal Sequences.
Before using them you need subprocess.run('', shell=True) (prior to Python 3.5, use subprocess.call). These sequences make possible what you are looking for.
Caution: Also original Microsoft, the documentation of Erase in Display and Erase in Line is partly faulty. The parameters 1 and 2 are reversed.
This should work (although, actually entering the password seems to destroy the layout):
import subprocess
subprocess.run('', shell=True)
print(' enter password : \0337', end='')
print('\n\n\t2 attempts remaining .\0338', end='')
x = input()
With Python 3 use;
print("...", end="")

Delete last printed character python

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

How to not issue a new line in Python 3 when entering text with input()

I'm making a basic utility in Python 3 where the user inputs a command and gets feedback printed out into the console. When entering data using the input() or sys.stdin.readline() functions this is what the command-line session may look like (including \r and \n characters)
1. What is your name:\n
2. <user input>\n
3. Your name is <variable>.\n
But, I would like to display a \r character after the user hits enter instead of the \n character, as shown on line 2. After the user had typed everything in and hit enter it would look like this
1. What is your name:\n
2. Your name is <variable>.\n
(because line 2 would have a \r character after the entered data, returning the cursur back to the far left)
Does anybody know of a way I might accomplish this?
Well, I discovered this method although I am almost cirtain that the msvcrt module is for Windows only.
import msvcrt
import sys
def msgInput(prompt):
print(prompt, end='')
data= b''
while True:
char= msvcrt.getch()
if char != b'\r':
print(char.decode(), end='')
sys.stdout.flush()
data= data+char
else:
print('\r', end='')
break
return data.decode()
If anybody knows of any cross-platform methods, please share.
Update - Unfortunately this method has many limitations, such as the user cannot navigate the entered text with the arrow keys.
Well, I believe I found the solution you wanted:
strng=input("Enter String - ")
Where strng is just a variable to hold the input response. This will return the string in the interpreter Enter String - (without any quote) and allow you to save the response in the variable strng.

exe created using cx_freeze not working properly

use=input('what do you wanna do \n1.press w to create a new file\n2.press r to read a file:\n')
if use=='r':
read()
elif use=='w':
write()
else :
print('OOPS! you enter a wrong input\n')
user()
when i run this code using IDLE it runs properly but when i created a exe of this python file using cx_freeze then the if and elif conditions are not working for 'r' and 'w' respectively. for any input it always goes to the else statement.
I am using python 3.2 and cx_freeze 3.2
Just for a quick test, I did this:
use = input("test input here: ")
for i in use:
print(ord(i))
The result, if you type in "hello", is the ascii character codes for hello, plus "13". This is \r, the return character, which is being added to your string. This doesn't happen under Linux and is the result of the fact on Windows a newline is \r\n as opposed to just \n.
The workaround for you would be to do something like:
use = input("test input: ").strip("\r")
strip() is a string object method that'll remove characters from the end and beginnings of strings.
Notes:
The use of ord() in the above example is probably not best practise - see Unicode.
If you ever write GUIs and use cx_freeze, don't use print() or input() - on Windows the standard input/output handles don't exist for GUI apps at all. That tripped me up for a while with cx_freeze + gui code. Just a note for when you get there.

Categories

Resources