Search code examples
pythonstringlistcalculatordecimal-point

How to convert a string that includes decimal point to a list in python


The input string is like this

a=(2.5+6/3.7*2.09)

It needs to be converted to a list to be used as a calculator

b=['2.5','+','6','/','3.7','*','2.09']

How to convert the string a to a list like b, such that the decimal point numbers are considered as a single number not like ['2','.','0','9']


Solution

  • You can use split a string by Multiple Delimiters :

    import re
    a="2.5+6/3.7*2.09"
    print(re.split('\+|\*|/',a))
    

    output:

    ['2.5', '6', '3.7', '2.09']
    

    Full solution:

    import re
    a="2.5+6/3.7*2.09"
    pattern='\+|\/+|\*'
    strings=re.split('\+|\*|/',a)
    sym=re.findall(pattern,a)
    new=[]
    for i in range(len(strings)):
        new.append(strings[i])
        try:
            new.append(sym[i])
        except IndexError:
            pass
    print(new)
    

    output:

    ['2.5', '+', '6', '/', '3.7', '*', '2.09']