Use the csv
module to handle input like that; it handles quoting, can be taught about leading whitespace, and trailing whitespace can be removed afterwards:
import csv
reader = csv.reader(inputstring.splitlines(), skipinitialspace=True)
row = next(reader) # get just the first row
res = [c.strip() for c in row]
Demo:
>>> import csv
>>> inputstring = '"filename.txt", 1234,8973,"Some Description "'
>>> reader = csv.reader(inputstring.splitlines(), skipinitialspace=True)
>>> row = next(reader)
>>> [c.strip() for c in row]
['filename.txt', '1234', '8973', 'Some Description']
This has the added advantage that you can have commas in the values, provided they are quoted:
>>> with_commas = '"Hello, world!", "One for the money, two for the show"'
>>> reader = csv.reader(with_commas.splitlines(), skipinitialspace=True)
>>> [c.strip() for c in next(reader)]
['Hello, world!', 'One for the money, two for the show']
The csv.reader()
object takes an iterable as the first argument; I used the str.splitlines()
method to turn a (potentially multiline) string into a list; you could also just use [inputstring]
if your input string is always just one line.