Python Regex replace


Question

Hey I'm trying to figure out a regular expression to do the following.

Here is my string

Place,08/09/2010,"15,531","2,909",650

I need to split this string by the comma's. Though due to the comma's used in the numerical data fields the split doesn't work correctly. So I want to remove the comma's in the numbers before running splitting the string.

Thanks.

1
24
11/17/2011 7:11:03 PM

Accepted Answer

new_string = re.sub(r'"(\d+),(\d+)"', r'\1.\2', original_string)

This will substitute the , inside the quotes with a . and you can now just use the strings split method.

49
12/23/2013 5:27:28 PM

>>> from StringIO import StringIO
>>> import csv
>>> r = csv.reader(StringIO('Place,08/09/2010,"15,531","2,909",650'))
>>> r.next()
['Place', '08/09/2010', '15,531', '2,909', '650']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon