Home > front end >  How do I take out the 2 or more-digit numbers in a python string?
How do I take out the 2 or more-digit numbers in a python string?

Time:04-17

I am trying to add up the numbers in the string like such: 76 977 I need to add up these numbers, but I get a 1st 2nd digit sum.

My code:

a = list(input())
a.remove(' ')
print(a)
print(int(a[0]) int(a[1]))

CodePudding user response:

use the split function:

a = "76 977"
b=a.split(" ")
sum = 0
for num in b:
    sum  = int(num)
print(sum)

CodePudding user response:

Try a.split(' '), it takes a string and returns a list of strings seperated by that string.

a = input()
b = a.split(' ')
print(b)
print(int(b[0]) int(b[1]))

CodePudding user response:

Slightly different answer :

string = '76 977'
print(sum([int(x) for x in string.split()]))

CodePudding user response:

        print('Enter string of numbers : ')
    
    a = list(input())
    print('\nThis is character list of entered string : ')
    print(a)
    numbers = []
    num = 0
    
    for x in a:
        # ord() is used to get ascii value
        # of character ascii value of 
        # digits from 0 to 9 is 48 to 57 respectively.
        if(ord(x) >= 48 and ord(x) <= 57):
            #this code is used to join digits of 
            #decimal number(base 10) to number
            num = num*10
            num = num int(x)
        elif num>0 :
            # all numbers in string are stored in 
            # list called numbers 
            numbers.append(num)
            num = 0
            
    if num>=0:
        numbers.append(num)
        num = 0
        
    print('\nThis is number list : ', numbers)
    sum=0
    for num in numbers:
        # all numbers are added and and sum
        # is stored in variable called sum 
        sum = sum num
    print('Sum of numbers = ', sum)

enter image description here

  • Related