Skip to content Skip to sidebar Skip to footer

Split A List Up To A Maximum Number Of Elements

I was wondering if someone could help me with the following problem: I have a text file that I split into rows and columns. The text file contains a variable amount of columns, how

Solution 1:

You are almost there. split takes (as its second argument) the maximum number of splits to do.

https://docs.python.org/3.8/library/stdtypes.html#str.split

rot = ['6697 1100.0   90.0    0.0    0.0  6609 !',
'701  0.0   0.0    83.9   1.5    000 !AFR-AHS IndHS-AFR']

for i in range(len(rot)):
    rot[i]=rot[i].split(maxsplit=6)

Note: You want six splits, which results in seven columns. You'll need to do some extra processing if the text can have fewer than seven columns though.

Post a Comment for "Split A List Up To A Maximum Number Of Elements"