T.P.
T.P.

Reputation: 103

How to take user input when it is seperated by any number of spaces and line breaks in python?

I have been trying to take integer inputs seperated by any number of white spaces or line breaks. I know how to take space seperated outputs and outputs having line breaks. In C based languages we don't have to care about where the input is, it automatically takes the input when found, but I don't think this is the case with Python(correct me if I am wrong). Can anybody help?

I tried using a While statement till True and using a try statement in it. But it doesn't work.

a = []
try:
    while(True):
        a.append(int(input()))
except:
    pass
print(a) 

when i input 12 12 12 it returns an empty list. If i remove the int in the input it returns a list [12 12, 12].

Upvotes: 1

Views: 4031

Answers (3)

Chetan Vashisth
Chetan Vashisth

Reputation: 456

Try this: The Shortest way possible

a = []
s=input()

while s != '':  
    i = s.split()       
    [a.append(int(j)) for j in i]
    s=input()

print(a)

Input:

1 2 3
4 5
6

Output:

[1, 2, 3, 4, 5, 6]

You can also try:

a = []
s=input()

while s != '':  
    i = s.split()       
    a.extend(map(lambda s: int(s),i))
    s=input()

print(a)

Upvotes: 1

MegaEmailman
MegaEmailman

Reputation: 545

Wait, so I think I understand it now. You want to accept any amount of input, but save each input separated by whitespace as its own entry? There is actually a string method for that. Here's an example script for it. It's not the best, but it demonstrates the method pretty well.

list = []
string = "user input goes here"
splitString = string.split()
for word in splitString:
    list.append(word)
print(list)

Output:

["user", "input", "goes", "here"]

The string.split() method uses space by default, but you can specify another delimiter like the # sign.

List = []
String = "Hi#my#name#is#bob"
newString = String.split("#")
for word in newString:
    list.append(word)

EDIT: Here is a full working implementation that will work whether the thing separating two inputs is whitespace, newlines, or anything else you'd like.

import re
list = []
while True:
    string = input()
    if string == "break":
        break
    splitString = re.split("[\s | \r\n]", string)
    for word in splitString:
        list.append(word)
    cleanList = []
    for word in list:
        if word != '':
            cleanList.append(word)
print(cleanList)

Input:

12 94 17
56
3

Output:

[12, 94, 17, 56, 3]

Functional proof: Click here

Upvotes: 1

sam
sam

Reputation: 1896

Hope you will some insight in this example & have added my personal view of how to code.

Firstly, giving input with multi-spaces is understandable but not multi-lines. Prefer taking input one by one.

For testing & debugging purposes, prefer separate collecting user and processing input data.

Now, say you have collected your user input and stored as data using raw_input, which is handy when you need to collect multiline inputs. Please explore raw_input, it is supported in Python3 and Python2.

>>>
>>> data = '''12
...
... 12       12
...
...
... 12'''
>>> data
'12 \n\n12       12\n\n\n12'
>>> print(data)
12

12       12


12

step1: clear all line separations

>>> double_spaces = '  '
>>> single_space = ' ' 
>>> data = data.strip().replace('\n', single_space)
>>> data
'12   12       12   12'

step2: Fix multiple spaces

>>> while double_spaces in data:
...     data = data.replace(double_spaces, single_space)
...
>>> data
'12 12 12 12'
>>> print(list(map(int, data.split()))
...
... )
[12, 12, 12, 12]
>>>

Problems with you code

>>> a = []
>>> try:
...     while(True):
...         a.append(int(input()))
... except:
...     pass
...
12
1
12  12
>>> a
[12, 1]
>>>

When you enter 12 12, below is supposed to happen.

>>> int('12 12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12 12'

Since this code had bad exception handling except:, your use case is returning an empty list as expected.

Since I have changed the input, you see this difference.

Upvotes: 0

Related Questions