Search code examples
pythonstringvalueerror

How can i divide string based on matematical symbole?


At the start sorry for my english. I wrote some code in PyCharm where i'am trying to divide string with mathematical operators such as +,-, itp and numbers but at the same time saving position of the mathematical operators and what they were.

string = '1234 - 4332 / 23 + 13 + 12 + 3213'
znaki = []
znakik = []
ilznak = string.count('+')+string.count('-')+string.count('/')+string.count('*')
i = [0,0,0,0]
num = string.split(" ")
print(num)
x = len(num)
while num.count('+')+i[0] >= i[0]:
    znaki.append('+')
    znakik.append(num.index('+'))
    print(znakik)
    num.pop(num.index('+'))
    i[0] = i[0] + 1
    print(num)

It's work sometimes but sometimes it gives me error :

Traceback (most recent call last):
  File "D:/Prog/Python/Działaniastring.py", line 11, in <module>
    znakik.append(num.index('+')+i[0])
ValueError: '+' is not in list

Why is it that it pops sometimes but not always and what causes it?


Solution

  • Welcome to Stackoverflow. As a beginner in python you should definitely consider using python visualizer to understand the entire logic of the code. see here

    Running your code gives this output:

    ['1234', '-', '4332', '/', '23', '+', '13', '+', '12', '+', '3213']
    [5]
    ['1234', '-', '4332', '/', '23', '13', '+', '12', '+', '3213']
    [5, 6]
    ['1234', '-', '4332', '/', '23', '13', '12', '+', '3213']
    [5, 6, 7]
    ['1234', '-', '4332', '/', '23', '13', '12', '3213']
    

    And clearly when there remains no more '+' you would get the error that

    ValueError: '+' is not in list

    So how does this happen?

    1    znakik.append(num.index('+'))
    2    num.pop(num.index('+'))
    

    In line 2 you pop the '+' from the array on each iteration, i,e. the index value stored in the znkakik array. Once you do this for all you end up with no more '+', and then the error.