'How to write a python computer program that will take any valid arithmetic expression as a string and will output a list(or array of string)? [duplicate]

How to write a python computer program that will take any valid arithmetic expression as a string and will output a list (or array of string) of individual objects of the expression such as numbers, operators, variables, and parenthesis?

Example#1:

Input:

x + 2

Output:

["x", "+", "2"]

Example#2:

Input:

2 * count + 17

Output:

["2", "*", "count", "+", "17"]

Example#3:

Input:

(12+x1)*(y2-15)

Output:

["(", "12", "+", "x1", ")", "*", "(", "y2", "-", "15", ")"]


Solution 1:[1]

You can use regular expression:

import re
input_str = "(12+x1)*(y2-15)"
output = list(filter(lambda x: x.strip() not in [''], re.split('([^a-zA-Z0-9])', input_str)))
print(output)

Output:

['(', '12', '+', 'x1', ')', '*', '(', 'y2', '-', '15', ')']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman