我有下面列出的字符串
str = ['"Consumers_Of_Product": {"count": 13115}']
如何提取数字13115,因为它会改变,因此它总是等于var。换句话说,如何从此字符串中提取此数字?
我以前做过的大多数事情都没有奏效,我认为这是由于语法原因造成的。我正在运行Python 2.7。
答案 0 :(得分:3)
如果您只想提取该数字,只要该字符串中没有其他数字,您就可以使用regex
。由于@ TigerhawkT3答案中提到的原因,我将str
重命名为s
。
import re
s = ['"Consumers_Of_Product": {"count": 13115}']
num = re.findall('\d+', s[0])
print(num[0])
13115
答案 1 :(得分:2)
在该列表中的单个元素上使用ast.literal_eval
(你不应该调用str
,因为它掩盖了内置函数,而且它不是一个字符串),在花括号内(因为它似乎是一个字典元素):
>>> import ast
>>> s = ['"Consumers_Of_Product": {"count": 13115}']
>>> ast.literal_eval('{{{}}}'.format(s[0]))
{'Consumers_Of_Product': {'count': 13115}}
答案 2 :(得分:0)
但建议使用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
记住TigerhawkT3说明为什么不应该使用
str
答案 3 :(得分:0)
您可以使用regular expression
从字符串中提取所需内容。以下是有关HOW TO use Regular expression in python
示例代码:
import re
m = re.search(r'(\d+)', s[0])
if m:
print m.group()
else:
print 'nothing found'
您的字符串看起来像JSON
字符串,因此如果您正在处理json字符串,则可以使用json
包来提取字段count
的值
此处的示例代码(您需要使用{}
或数组[]
包装您的字符串):
import json
obj = json.loads('{"Consumers_Of_Product": {"count": 13115}}')
print(obj['Consumers_Of_Product']['count'])