Split from operator while conserving operators

Viewed 44

i want to separate the numbers and operator in string how can i do it ?

I am using split and getting numbers but i am not able to get the operator This code only works when operator is '+' otherwise it gives an error!

T = "123+456"
op = '+' or '-'
for i in range(T):
    n = input()
    n1,n2 =  n.split(op)
    print(n1)
    print(n2)
3 Answers

You can use regex to find both numbers and operators present in the string via r'(\d+)|([+\-\*/])' which matches either one or more digits, or an operator out of +,-,*,\

import re

def get_num_op(s):

    #Get all matches
    matches = re.findall(r'(\d+)|([+\-\*/])', s)
    #[('123', ''), ('', '+'), ('456', ''), ('', '*'), ('7', ''), ('', '*'), ('8', '')]

    #Remove empty matches from the list
    matches = [item for t in matches for item in t if item]

    return matches

print(get_num_op("123+456"))
print(get_num_op("123+45*6/7"))

The output will be

['123', '+', '456']
['123', '+', '45', '*', '6', '/', '7']

You can split this with re:

import re

T = "123+456"
re.split('((\w)[0-9]*)', T)

out:['', '123', '+', '456', '']

This code works fine with "+","-","*","/" this set of operators.It will give you operand1, operand2 and the operator.

user_input="12-23"
operator_list = ["+","-","*","/"]

input_list = [x for x in user_input]

for operator in operator_list:
    if operator in input_list:
        index = input_list.index(operator)
        break

operand1 = user_input[:index]
operand2 = user_input[index+1:]
print(operand1 , operator, operand2)

Output

12 - 23

Related