Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting numbers in a string [duplicate]

Tags:

python

string

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.

like image 461
jaganath Avatar asked Dec 04 '25 19:12

jaganath


2 Answers

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
like image 138
John Kugelman Avatar answered Dec 06 '25 08:12

John Kugelman


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)
like image 26
Andrii Bovsunovskyi Avatar answered Dec 06 '25 08:12

Andrii Bovsunovskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!