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?
Most things I've done previously have not worked and I think that is due to the syntax. I'm running Python 2.7.
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
Use ast.literal_eval
on the single element in that list (which you shouldn't call str
because it masks the built-in, and it isn't a string anyway), within curly braces (as it seems to be a dictionary element):
>>> import ast
>>> s = ['"Consumers_Of_Product": {"count": 13115}']
>>> ast.literal_eval('{{{}}}'.format(s[0]))
{'Consumers_Of_Product': {'count': 13115}}
You have 3 options
But it's recommended to use json
lib
import json
s = ['"Consumers_Of_Product": {"count": 13115}']
s[0] = '{' + s[0] + '}'
my_var = json.loads(s[0]) # this is where you translate from string to dict
print my_var['Consumers_Of_Product']['count']
# 13115
remembering what TigerhawkT3 said about why you shouldn't use
str
You can use regular expression
to extract anything you want from a string. Here is a link about HOW TO use Regular expression in python
sample code here:
import re
m = re.search(r'(\d+)', s[0])
if m:
print m.group()
else:
print 'nothing found'
Your string looks something like a JSON
string, so if you are dealing with json string, you can make use of json
package to extract the value for field count
sample code here (you need to wrap your string with {}
or array []
):
import json
obj = json.loads('{"Consumers_Of_Product": {"count": 13115}}')
print(obj['Consumers_Of_Product']['count'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.