Can Python remove double quotes from a string, when reading in text file? Can Python remove double quotes from a string, when reading in text file? python python

Can Python remove double quotes from a string, when reading in text file?


for line in open(name, "r"):    line = line.replace('"', '').strip()    a, b, c, d = map(float, line.split())

This is kind of bare-bones, and will raise exceptions if (for example) there aren't four values on the line, etc.


There's a module you can use from the standard library called shlex:

>>> import shlex>>> print shlex.split('5.6  4.5  6.8  "6.5"')['5.6', '4.5', '6.8', '6.5']


The csv module (standard library) does it automatically, although the docs isn't very specific about skipinitialspace

>>> import csv>>> with open(name, 'rb') as f:...     for row in csv.reader(f, delimiter=' ', skipinitialspace=True):...             print '|'.join(row)5.6|4.5|6.8|6.55.4|8.3|1.2|9.3