3

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.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
jaganath
  • 51
  • 1
  • 3
  • Do you need an explicit variable for each number or do you just want to sum every integer? Would an array of numbers be alright (you could reduce over it)? If so, python has a split method on all strings in which you pass a character "," and it will return an array of the values separated by the comma. – Erik Hinton Oct 23 '11 at 16:31
  • by number i mean the integer..any ways i got the desired answer,thank u – jaganath Oct 23 '11 at 16:54

3 Answers3

9

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
4

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

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.

PaulMcG
  • 62,419
  • 16
  • 94
  • 130