Monday, December 26, 2016

How to split single line input-Python


Sometimes we have to give multiple inputs in one single line separated with spaces which is a burden to the programmers. However, this problem can be easily handled in python using inbuilt python functions and attributes.
The inbuilt python function that can be used is the split () function. The output of this function is always a LIST. So we have to convert it accordingly to our use.

Explanation:
Consider I am giving some input with spaces in between them like the following
1 2 3 4 5 6
Now if I apply the split() function then it will result in the following output
['1', '2', '3', '4', '5', '6']

EXAMPLE:
         Ex:1-Only with numbers
            >>> a=input()
1 2 3 4 5 6
>>> print(a)
1 2 3 4 5 6
>>> a.split()
['1', '2', '3', '4', '5', '6']


         Ex:2-With numbers and strings
            >>> a=input()
1 2 3 Hello
>>> print(a)
1 2 3 Hello
>>> a.split()
['1', '2', '3', 'Hello']

Points:                                                                                                                                                                
-Output of spilt function is always a list.
-Each value in the list is converted into string value so need to convert them expicitly.