'Seperate and add two numbers from a string in python (user input)

I am trying to take a string from user input like ("what is 1 + 1") separate the letters from numbers and then add the 2 numbers. I have tried the below code buti still cant fiqure out how to add the two 1s.

def splitString(str):

alpha = ""
num = ""
special = ""
for i in range(len(str)):
    if(str[i].isdigit()):
        num = num+ str[i]
    elif((str[i] >= 'A' and str[i] <= 'Z') or
         (str[i] >= 'a' and str[i] <= 'z')):
        alpha += str[i]
    else:
        special += str[i]

print(alpha)
print(num )
print(special)


            
    

if name == "main":

str = "what is 1 + 1"
splitString(str)


Solution 1:[1]

my_str = "what is 1 + 1"
x = []
str_list = my_str.split(" ")
for i in str_list:
    if i.isDigit():
        x.append(int(i))

sum_integers = 0
for i in x:
    sum_integers += i

print(sum_integers)

try this, I did not run it.

Solution 2:[2]

The ".split" function will simplify your code a lot. I encourage you to look at this link https://www.w3schools.com/python/ref_string_split.asp

Solution 3:[3]

I might suggest using itertools.groupby as a starting point, e.g.:

>>> import itertools
>>> def split_alpha_num(s: str) -> list[str]:
...     return ["".join(g).strip() for _, g in itertools.groupby(s, lambda s:(s.isalpha(), s.isdecimal()))]
...
>>> split_alpha_num("what is 1 + 1")
['what', '', 'is', '', '1', '+', '1']

From there, you could iterate over the string, discard elements that aren't either numbers or mathematical operators, and try to do something with what remains. The exact approach depends on the complexity of the inputs that you want your code to be able to handle; solving this type of problem in the very general case is not trivial.

Solution 4:[4]

you should make the variable num a list, and then add to that list all of the numbers

like that

def splitString(str):
    alpha = ""
    num = []
    special = ""
    for i in range(len(str)):
        if(str[i].isdigit()):
            num.append(int(str[i]))
        elif((str[i] >= 'A' and str[i] <= 'Z') or
            (str[i] >= 'a' and str[i] <= 'z')):
            alpha += str[i]
        else:
            special += str[i]

    print(alpha)
    print(num)
    print(special)

that way later you could use the special variable to determine what to do with thous numbers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 White_Sirilo
Solution 2 Ansh Chandarana
Solution 3 Samwise
Solution 4 asimon