How to extract number from text in python?
<p>I have the string listed below</p>

<pre><code>str = ['"Consumers_Of_Product": {"count": 13115}']
</code></pre>

<p>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?</p>

<p>Most things I've done previously have not worked and I think that is due to the syntax. I'm running Python 2.7.</p>

<p>You can use <code>regular expression</code> to extract anything you want from a string. Here is a link about <a href="https://docs.python.org/2/howto/regex.html" rel="nofollow">HOW TO use Regular expression in python</a></p>

<p>sample code here:</p>

<pre><code>import re
m = re.search(r'(\d+)', s[0])
if m:
    print m.group()
else:
    print 'nothing found'
</code></pre>

<p>Your string looks something like a <code>JSON</code> string, so if you are dealing with json string, you can make use of <code>json</code> package to extract the value for field <code>count</code></p>

<p>sample code here (you need to wrap your string with <code>{}</code> or array <code>[]</code> ):</p>

<pre><code>import json
obj = json.loads('{"Consumers_Of_Product": {"count": 13115}}')
print(obj['Consumers_Of_Product']['count'])
</code></pre>

python string python-2.7 integer