Ronald Rojas
Ronald Rojas

Reputation: 13

How does raw_input treat ENTER or \n

I have a long list of numbers that I would like to input into my code through a raw_input. It includes numbers that are spaced out through SPACES and ENTER/RETURN. The list looks like this . When I try to use the function raw_input, and copy paste the long list of numbers, my variable only retains the first row of numbers. This is my code so far:

def main(*arg):
    for i in arg:
        print arg

if __name__ == "__main__": main(raw_input("The large array of numbers"))

How can I make my code continue to read the rest of the numbers? Or if that's not possible, can I make my code acknowledge the ENTER in any way?

P.s. While this is a project euler problem I don't want code that answers the project euler question, or a suggestion to hard code the numbers in. Just suggestions for inputting the numbers into my code.

Upvotes: 1

Views: 506

Answers (2)

flen
flen

Reputation: 2386

If I understood your question correctly, I think this code should work (assuming it's in python 2.7):

sentinel = '' # ends when this string is seen
rawinputtext = ''
for line in iter(raw_input, sentinel):
    rawinputtext += line + '\n' #or delete \n if you want it all in a single line
print rawinputtext

(code taken from: Raw input across multiple lines in Python )

PS: or even better, you can do the same in just one line!

rawinputtext = '\n'.join(iter(raw_input, '') #replace '\n' for '' if you want the input in one single line

(code taken from: Input a multiline string in python )

Upvotes: 1

Abhijit
Abhijit

Reputation: 63727

I think what you are actually looking for is to directly read from stdin via sys.stdin. But you need to accept the fact that there should be a mechanism to stop accepting any data from stdin, which in this case is feasible by passing an EOF character. An EOF character is passed via the key combination [CNTRL]+d

>>> data=''.join(sys.stdin)
Hello
World
as
a
single stream
>>> print data
Hello
World
as
a
single stream

Upvotes: 0

Related Questions