拆分不带空格的十进制字符串 - Python

Splitting an unspaced string of decimal values - Python

一个糟糕的人给了我这样的字符串

values = '.850000.900000.9500001.000001.50000'

我需要拆分它以创建以下列表:

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

我知道我只处理小于 1 的数字我可以使用代码

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

但是在这种情况下,字符串中的数字大于 1,splitvalue 最终会是

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

那么有没有一种方法可以用多个定界符拆分字符串,同时根据遇到的定界符以不同方式拆分字符串?

假设小数点前的值小于10,则有,

values = '0.850000.900000.9500001.000001.50000'

result = list()
last_digit = None 

for value in values.split('.'):
    if value.endswith('0'):
        result.append(''.join([i for i in [last_digit, '.', value] if i]))
        last_digit = None
    else:
        result.append(''.join([i for i in [last_digit, '.', value[0:-1]] if i]))
        last_digit = value[-1]

if values.startswith('0'):
    result = result[1:]

print(result)
# Output
['.850000', '.900000', '.950000', '1.00000', '1.50000']

我认为这更接近固定宽度的格式字符串。试试这样的正则表达式:

import re

str = "(\d{1,2}\.\d{5})"
m = re.search(str, input_str)
your_first_number = m.group(0)

在剩余的字符串上重复此操作以消耗所有数字。

对于固定/可变字符串,您可以尝试类似的方法:

values = '0.850000.900000.9500001.000001.50000'
str_list = []

first_index = values.find('.')
while first_index > 0:
    last_index = values.find('.', first_index + 1)
    if last_index != -1:
        str_list.append(values[first_index - 1: last_index - 2])
        first_index = last_index
    else:
        str_list.append(values[first_index - 1: len(values) - 1])
        break
print str_list

Output:

['0.8500', '0.9000', '0.95000', '1.0000', '1.5000']

Assuming that there will always be a single digit before the decimal.

Please take this as a starting point and not a copy paste solution.

如何使用re.split():

import re

values = '0.850000.900000.9500001.000001.50000'

print([a + b for a, b in zip(*(lambda x: (x[1::2], x[2::2]))(re.split(r"(\d\.)", values)))])

输出

['0.85000', '0.90000', '0.950000', '1.00000', '1.50000']
>>> import re
>>> source = '0.850000.900000.9500001.000001.50000'

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

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

拆分基于寻找“{任何东西,双零,一个 运行 个零(后跟一个非零)”}。

这里的数字是固定宽度的,即6,如果包括点就是7。得到从0到7和7到14的切片等等。因为我们不需要初始零,所以我使用切片values[1:]进行提取。

values = '0.850000.900000.9500001.000001.50000'
[values[1:][start:start+7] for start in range(0,len(values[1:]),7)]
['.850000', '.900000', '.950000', '1.00000', '1.50000']

测试;

''.join([values[1:][start:start+7] for start in range(0,len(values[1:]),7)]) == values[1:]
True