Samar Yadav Samar Yadav - 3 months ago 7
Python Question

Making python interpret spaces as newline characters

I am not sure about input format that user will enter. There are two possibities:

code:

n=int(input("enter the no of workers \n"))
print("enter the names of workers")
NameList=[]
for i in range(n):
NameList.append(input())
print(NameList)


possibility 1:

enter the no of workers

4

enter the names of workers

name1

name2

name3

name4

['name1', 'name2', 'name3', 'name4']

working great...!!

possibility 2:

input will be :

enter the no of workers

4

enter the names of workers

name1 name2 name3 name4

in this case my code will fail. I'll need to write different code( i know how to write that ;) ) to accept this format of input.

So is there anyway that one code will work for both input formats. By treating spaces as Enter. Thanks

Answer

If a worker name can't include a space, you can check that and change the behavior accordingly.

This will even work if the user combine the 2 options (e.g. entering 'a' and then 'b c'), although it is not perfect (it is possible to get more than n names, for example if n == 3 and inputting 'a b' and 'c d')

n = int(input("enter the no of workers \n"))
print("enter the names of workers")
NameList = []
while len(NameList) < n:
    worker_name = input()
    if ' ' in worker_name:
        if NameList:
            NameList.extend(worker_name.split())
        else:
            NameList = worker_name.split()
    else:
        NameList.append(worker_name)
print(NameList)
Comments