Q:

Split from operator while conserving operators

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)

A:

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']

