David Chen David Chen - 8 months ago 55
Python Question

Python regular expression dot character

I have solved this problem via Wiktor Stribi┼╝ew's suggestion.

Edited: I only need to extract the first element of the list at a time, because I need to do other operations on that number. I use a loop in my code just for testing.

I want to split an arithmetic expression into a list of numbers.

For example: 1+0.2-(3^4)*5 -> ['1', '0.2', '3', '4', '5']

I use the re library in python, but the expression is split with a dot character '.' although I do not include '.' in the delmiters.

Namely, when input is 1+0.2, the output will be ['1', '0', '2'], which should be ['1', '0.2']

The code is below:

import re

delims = re.compile(r"[+-/*///^)]")

while True:
string = input()
res = list()
i = 0
while i < len(string):
if string[i] >= '0' and string[i] <= '9':
num_str = delims.split(string[i:], 1)[0]
i += len(num_str) - 1
i += 1

I really appreciate any opinion to this question!


The reason your approach is not working is that you create a character range with +-/ which contains the dot. I also think you are overcomplicating things.

import re
str = '1+0.2-(3^4)*5'
res = re.split(r'[-+()/*^]+', str)

will output ['1', '0.2', '3', '4', '5']

Please note that this approach won't handle negative numbers correctly.