简体   繁体   中英

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)
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.

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

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

>>> 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM