Skip to content Skip to sidebar Skip to footer

Python: Split Line By Comma, Then By Space

I'm using Python 3 and I need to parse a line like this -1 0 1 0 , -1 0 0 1 I want to split this into two lists using Fraction so that I can also parse entries like 1/2 17/12 , 1

Solution 1:

The problem is that your file has a line without a " , " in it, so the split doesn't return 2 elements.

I'd use split(',') instead, and then use strip to remove the leading and trailing blanks. Note that str(...) is redundant, split already returns strings.

X = [elem.strip() for elem in line.split(",")]

You might also have a blank line at the end of the file, which would still only produce one result for split, so you should have a way to handle that case.

Solution 2:

With valid input, your code actually works.

You probably get an invalid line, with too much space or even an empty line or so. So first thing inside the loop, print line. Then you know what's going on, you can see right above the error message what the problematic line was.

Or maybe you're not using stdin right. Write the input lines in a file, make sure you only have valid lines (especially no empty lines). Then feed it into your script:

python myscript.py < test.txt

Solution 3:

How about this one:

pairs = [line.split(",") for line in stdin]
num = [fraction(elem[0]) for elem in pairs if len(elem) == 2]
den = [fraction(elem[1]) for elem in pairs if len(elem) == 2]

Post a Comment for "Python: Split Line By Comma, Then By Space"