deppfx
deppfx

Reputation: 751

How to take multiple multiline input variables in Python?

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.

Upvotes: 2

Views: 6887

Answers (6)

Anagha V Raj
Anagha V Raj

Reputation: 17

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

Upvotes: 0

Artem Shenberg
Artem Shenberg

Reputation: 1

If you have mean read multiple variables from multiple inputs:

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

Upvotes: -1

Arindam Kundu
Arindam Kundu

Reputation: 1

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

Upvotes: -1

Amir Shabani
Amir Shabani

Reputation: 4197

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]

Upvotes: 7

VMRuiz
VMRuiz

Reputation: 1981

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]

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

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.

Upvotes: 0

Related Questions