Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to get user input without inserting a new line?

Tags:

I know I can stop print from writing a newline by adding a comma

print "Hello, world!",

But how do I stop raw_input from writing a newline?

print "Hello, ",
name = raw_input()
print ", how do you do?"

Result:

Hello, Tomas
, how do you do?

Result I want:

Hello, Tomas, how do you do?

like image 250
Hubro Avatar asked Aug 24 '11 10:08

Hubro


People also ask

How do you input without a new line in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you get user input on the same line in Python?

You can use a list comprehension to take n inputs in one line in Python. The input string is split into n parts, then the list comp creates a new list by applying int() to each of them.

How do we get user input from the keyboard?

The input() function gets user input (keyboard) and stores it into variable name. Here name is a variable. The print() function shows it to the screen. The user must press the enter key in the command line.


2 Answers

But how do I stop raw_input from writing a newline?

In short: You can't.

raw_input() will always echo the text entered by the user, including the trailing newline. That means whatever the user is typing will be printed to standard output.

If you want to prevent this, you will have to use a terminal control library such as the curses module. This is not portable, though -- for example, curses in not available on Windows systems.

like image 89
Ferdinand Beyer Avatar answered Sep 20 '22 13:09

Ferdinand Beyer


This circumvents it, somewhat, but doesn't assign anything to variable name:

print("Hello, {0}, how do you do?".format(raw_input("Enter name here: ")))

It will prompt the user for a name before printing the entire message though.

like image 25
Cassandra S. Avatar answered Sep 21 '22 13:09

Cassandra S.