2

Is it possible to take multiple newline inputs into multiple variables & declare them as int all at once?

To explain further what I am trying to accomplish, I know this is how we take space separated input using map:

>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5

Is there an equivalent for a newline? Something like:

a, b = map(int, input().split("\n"))

Rephrasing: I am trying to take multiple integer inputs, from multiple lines at once.

1
  • So you want something where 3 and 5 are on separate lines and the input keeps getting eaten? What should the resulting data structure look like? And when should you stop eating input? Commented May 19, 2017 at 6:43

6 Answers 6

7

As others have said it; I don't think you can do it with input().

But you can do it like this:

import sys
numbers = [int(x) for x in sys.stdin.read().split()]

Remeber that you can finish your entry by pressing Ctrl+D, then you have a list of numbers, you can print them like this (just to check if it works):

for num in numbers:
    print(num)

Edit: for example, you can use an entry like this (one number in each line):

1
543
9583
0
3

And the result will be: numbers = [1, 543, 9583, 0, 3]

Or you can use an entry like this:

1
53          3
3 4 3 
      54
2

And the result will be: numbers = [1, 53, 3, 4, 3, 54, 2]

Sign up to request clarification or add additional context in comments.

Comments

1

From what I understand from your question,you want to read the input until EOF character is reached and extract the numbers from it:

[ int(x.strip()) for x in sys.stdin.read().split() ]

It stop once ctrl+d is sent or the EOF characted on the entry is reached.

For example, this entry:

1 43 43   
434
56 455  34
434 

[EOF]

Will be read as: [1, 43, 43, 434, 56, 455, 34, 434]

Comments

0

You really cannot, input and raw_input stop reading and return when a new line is entered; there's no way to get around that from what I know. From inputs documentation:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

A viable solution might be calling input in a loop and joining on '\n' afterwards.

Comments

0
import sys
print("Enter your lines, then do Ctrl+Z once finished")
text = sys.stdin.read()
print(text)

Comments

-1

a, b = (int(input()) for _ in range(2))

Comments

-1

If you have mean read multiple variables from multiple inputs:

a, b, c = map(int, (input() for _ in range(3)))

1 Comment

Multi line inputs can be multiple lines. It could be 1 line, 2 lines, 3 lines, or 10 lines. Why is your program limiting the input to 3 lines only? Also, the question asks for space separator. Did you consider that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.