Q:

Creating nested list in python for a string field

I have the following input data. 
I can create nested list for all other fields exept the last field. The last string field can also contains space in between words(example: Hello! welcome ).
input  = ['a1 a2 a3 a4 Hello! welcome','b1 b2 b3 b4 how are you','c1 c2 c3 c4 you are welcome']

Current output:   
[['a1', 'a2', 'a3', 'a4', 'Hello!', 'welcome'],   
 ['b1', 'b2', 'b3', 'b4', 'how', 'are', 'you'],   
 ['c1', 'c2', 'c3', 'c4', 'you', 'are', 'welcome']] 

Expected output:
[['a1', 'a2', 'a3', 'a4','Hello! welcome'],     
 ['b1', 'b2', 'b3', 'b4','how are you'],   
 ['c1', 'c2', 'c3', 'c4','you are welcome']]    

The below lines of code produces the current output as above but i need to convert the code to get the expected result. Can any one please let me know the way to achieve the expected result.
for ix in range(len(input) ):
    nested.append(input[ix:ix + 1])

for i in range(len(nested)):
    list1.append(nested[i][0].split())

A:

You can use re.split for that purpose:
import re

input  = ['a1 a2 a3 a4 Hello! welcome','b1 b2 b3 b4 how are you','c1 c2 c3 c4 you are welcome']

res=[re.split(" ", el, maxsplit=4) for el in input]

print(res)

Output:
[['a1', 'a2', 'a3', 'a4', 'Hello! welcome'], ['b1', 'b2', 'b3', 'b4', 'how are you'], ['c1', 'c2', 'c3', 'c4', 'you are welcome']]

[Program finished]

Ref: https://docs.python.org/2/library/re.html

A:

I assume that you meant each sublist only contains 5 elements and the last one can have space between words. If that was the case then you simply need to iterate through input list and split each string by only with maximum 5 elements (4 is the highest index)
input  = ['a1 a2 a3 a4 Hello! welcome','b1 b2 b3 b4 how are you','c1 c2 c3 c4 you are welcome']

list1 = []

for i in input:
    list1.append(i.split(' ', 4))

print(list1)

