Binary111 Binary111 - 1 month ago 9
Python Question

How to extract number from text in python?

I have the string listed below

str = ['"Consumers_Of_Product": {"count": 13115}']


How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do i extract this number from this string?

Please help, most things I've done previously have not worked and I think that is due to the syntax. I need a solution asap. (BTW I'm running Python 2.7)

Thanks, Anthony

Answer

If you just want to extract that number, provided there are no other numbers in that string, you can use regex. I renamed str to be s for the reason mentioned in @TigerhawkT3 answer.

import re
s = ['"Consumers_Of_Product": {"count": 13115}']
num = re.findall('\d+', s[0])
print(num[0])
13115
Comments