__author__ = 'Alex' import re; str_list = [] def fetch(ci,li,str): for k in range(len(ci)-1): if ci[k] > ci[k+1]: print(("li[k] = %s,li[k+1] = %s")%(li[k],li[k+1])) s = str[li[k]:li[k+1]+1] str_list.append(s) print (str_list) del ci[k] del ci[k] del li[k] del li[k] return str_list str = "1 - 2*(17-(60-30+(-40*2/5)*9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2)" count = 0 i_list = [] count_list = [] for i in range(len(str)): if str[i] == '(': # print ("i= ",i) count +=1 i_list.append(i) count_list.append(count) print (("i = %s ,count = %s ")%(i,count)) if str[i] == ')': # print ("i= ",i) count -=1 i_list.append(i) count_list.append(count) print (("i = %s ,count = %s ")%(i,count)) print (i_list) print (count_list) while len(count_list)>0: symbols_list = fetch(count_list,i_list,str) # print (int(symbols_list[1]))