1

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.

Jemshit
  • 9,501
  • 5
  • 69
  • 106
  • Why would you try to input the list via raw_input? I don't believe that is how you should go about doing this – Tim Apr 09 '15 at 17:11
  • Imagine that raw_input did read newlines - how would it know when to stop? – Eric Apr 09 '15 at 17:12
  • possible duplicate of [Raw input across multiple lines in Python](http://stackoverflow.com/questions/11664443/raw-input-across-multiple-lines-in-python) – Celeo Apr 09 '15 at 17:25
  • I've deleted my answer in favor of the better answer on that question. – Celeo Apr 09 '15 at 17:25

2 Answers2

1

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 )

flen
  • 1,905
  • 1
  • 21
  • 44
0

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
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • could you explain this a little more? I have never heard of stdin or the .join you put in front of it. – Ronald Rojas Apr 09 '15 at 17:41
  • @RonaldRojas: I though it was pretty straight forward. The standard input stdin is a file like iterable object for standard input. The ''.join, is the string join method which consumes the standard input until EOF is reached. EOF is reached when user deliberately enters [CNTRL]+d – Abhijit Apr 09 '15 at 18:10