How to extract all the numbers in a string?
For example, consider a string "66,55,66,57"
. I want to extract each numbers into separate variables and perform integer arithmetic.
How to extract all the numbers in a string?
For example, consider a string "66,55,66,57"
. I want to extract each numbers into separate variables and perform integer arithmetic.
You can use a list comprehension along with str.split
to break up the string and convert it to integers:
>>> string = "66,55,66,57"
>>> numbers = [int(x) for x in string.split(",")]
>>> print numbers
[66, 55, 66, 57]
Then you can do whatever you want with that list. For example:
>>> sum(numbers)
244
The proposal even earlier methods are not suitable if the string contains other delimiters or special characters. I suggest another method:
import re
s = '123 @, 421, 57&as241'
result = re.findall(r'[0-9]+', s)
in result: ['123', '421', '57', '241']
and if you want you can convert string values to int:
result_int = map(int, result)
Try this:
s = "66,55,66,57"
its = iter(s)
ints = []
while 1:
try:
ints.append(int(''.join(takewhile(str.isdigit, its))))
except ValueError:
break
Will give you a list of integers in ints
.