Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store multi-line input into a String (Python)

Tags:

python

Input:

359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861

my code :

print("Enter the array:\n")   
userInput = input().splitlines()
print(userInput)

my problem here is that, userInput only takes in the first line value but it doesn't seem to take in values after the first line?

like image 406
user1371784 Avatar asked May 03 '12 07:05

user1371784


2 Answers

You can use readlines() method of file objects:

import sys
userInput = sys.stdin.readlines()
like image 58
citxx Avatar answered Oct 03 '22 08:10

citxx


You can easily create one, using generators. Here is one such implementation. Note you can either press a blank return or any Keyboard Interrupt to break out of the inputloop

>>> def multi_input():
    try:
        while True:
            data=raw_input()
            if not data: break
            yield data
    except KeyboardInterrupt:
        return


>>> userInput = list(multi_input())
359716482
867345912
413928675
398574126

>>> userInput
['359716482', '867345912', '413928675', '398574126']
>>> 
like image 31
Abhijit Avatar answered Oct 03 '22 09:10

Abhijit