'How do I take out the 2 or more-digit numbers in a python string?
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]))
Solution 1:[1]
use the split function:
a = "76 977"
b=a.split(" ")
sum = 0
for num in b:
sum += int(num)
print(sum)
Solution 2:[2]
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]))
Solution 3:[3]
Slightly different answer :
string = '76 977'
print(sum([int(x) for x in string.split()]))
Solution 4:[4]
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)
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 | nfn |
| Solution 2 | GideonBear |
| Solution 3 | |
| Solution 4 | Nick Vu |

