Prevent python from printing a new line

I have this code in Python

inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))

which outputs

Enter in something: something
Input is something
, including the return

I am not sure what is going on; if I use variables that are independent of user input, I don't get a new line after formatting with a variable. I suspect Python might accept input on a new line when I hit return.

How can I make the input not include newlines so that I can compare them with other lines / characters? (e.g. something == 'a')

+3
source share
4 answers

- inputted. , strip("\r\n"), :

print("Input is {0}, including the return".format(inputted.strip("\r\n")))

, inputted , , , , inputted.

, inputted.replace("\r\n", "") .

+7

Eclipse. , PyDev, . - Eclipse , . script Python 3.1.1, inputted .

Python , input() GNU readline, stdin (.. TTY , ), .readline() stdin . , readline \n, . : CR-LF LF-CR ( )!

, script, , :

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

stdin ( Eclipse), stdin, test\r\ntest\r\n.

script Eclipse - . : Enter Eclipse CR-LF ( "\ r\n" ). "\ r" Eclipse .

, Windows : input() , ( ) GNU. stdin StringIO("test\r\n") input() "test\r", Eclipse ( ).

, ... , , - Eclipse.

+4

, rstrip.
inputted.rstrip ("\r\n")

+3
inputted = inputted.strip()

: , . :

import re
inputted = re.sub("[\n\r]+$", "", inputted)
+2
source

Source: https://habr.com/ru/post/1737837/


All Articles