Skip to content
Advertisement

How to split the integers and Operators characters from string in python?

I want to split the string into integers and operators for doing Infix expression evaluation in python.

Here is my string:

>>> s = (1-2+3)*5+10/2

I tried this to split:

>>>list(s)
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '1', '0', '/', '2']

This is wrong. Since ’10’ is splitted into ‘1’,’0′

I tried alternative:

>>> re.findall('[+-/*//()]+|d+',s)
['(', '1', '-', '2', '+', '3', ')*', '5', '+', '10', '/', '2']

This is also went wrong. Since ‘)*’ should be splitted into ‘)’, ‘*’

Could you help to split the operators and integers from the given expression?

Advertisement

Answer

This is not the best solution for infix. Remove the + after [] like:

import re
s = "(1-2+3)*5+10/2"
print re.findall('[+-/*//()]|d+',s)

['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '10', '/', '2']

Try the following link for correct solution: Simple Balanced Parentheses

from pythonds.basic.stack import Stack

def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()

def doMath(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2

print(postfixEval('7 8 + 3 2 + /'))

Keep in mind that this is a postfix implementation and its just for example. Do the infix by yourself and if you have any difficulties just ask.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement