grokworks grokworks - 1 year ago 56
Python Question

Splitting an unspaced string of decimal values - Python

An awful person has given me a string like this

values = '.850000.900000.9500001.000001.50000'

and I need to split it to create the following list:

['.850000', '.900000', '.950000', '1.00000', '1.500000']

I know that I was dealing only with numbers < 1 I could use the code

dl = '.'
splitvalues = [dl+e for e in values.split(dl) if e != ""]

But in cases like this one where there are numbers greater than 1 buried in the string, splitvalue would end up being

['.850000', '.900000', '.9500001', '.00001', '.50000']

So is there a way to split a string with multiple delimiters while also splitting the string differently based on which delimiter is encountered?

Answer Source
>>> import re
>>> source = '0.850000.900000.9500001.000001.50000'

>>> re.findall("(.*?00+(?!=0))", source)

['0.850000', '.900000', '.950000', '1.00000', '1.50000']

The split is based on looking for "{anything, double zero, a run of zeros (followed by a not-zero)"}.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download