我有以下列出的字符串。
str = ['"Consumers_Of_Product": {"count": 13115}']
如何提取数字13115,使它始终等于变量var。换句话说,如何从该字符串中提取此数字?
我之前尝试过的大部分方法都没有成功,我认为这是由于语法问题。我正在运行Python 2.7。
str = ['"Consumers_Of_Product": {"count": 13115}']
如何提取数字13115,使它始终等于变量var。换句话说,如何从该字符串中提取此数字?
我之前尝试过的大部分方法都没有成功,我认为这是由于语法问题。我正在运行Python 2.7。
如果您只想提取该数字,并且在该字符串中没有其他数字,则可以使用regex
。 我将str
重命名为s
,原因在于@TigerhawkT3的回答中提到。
import re
s = ['"Consumers_Of_Product": {"count": 13115}']
num = re.findall('\d+', s[0])
print(num[0])
13115
在该列表中的单个元素上使用ast.literal_eval
(不应将其称为str
,因为它遮盖了内置函数,而且它也不是一个字符串),并将其放在花括号中(因为它似乎是一个字典元素):
>>> import ast
>>> s = ['"Consumers_Of_Product": {"count": 13115}']
>>> ast.literal_eval('{{{}}}'.format(s[0]))
{'Consumers_Of_Product': {'count': 13115}}
你有3个选项
但建议使用json
库
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
str
。您可以使用正则表达式
从字符串中提取任何想要的内容。这里有一个关于如何在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'])
num
。您可以打印num[0]
来获取数字。 - Joe T. Boka