从python中的字符串中提取特定值

时间:2018-09-14 08:01:45

标签: python

下面是存储在str变量中的输出,我想提取它的基数值,我已经用简单的方法print str[15:18]提取了它,但是每次如果基数值变大,我都必须更改字符串值增加或减少。

输出:

{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}

存储在str:

str = response.text

预期输出:

Active: 483

1 个答案:

答案 0 :(得分:1)

有2种方法:

1。

In [10]: import ast
In [11]: s='{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}'
In [12]: ast.literal_eval(s)
In [13]: %timeit ast.literal_eval(s)['cardinality']
10000 loops, best of 3: 29.4 µs per loop

2。

In [14]: import json
In [15]: s='{"cardinality":483,"timestamp":15369087280,"deltas":{"week_over_week":{"delta_fraction":0.047722318876,"last_week_value":146}}}'
In [16]: %timeit json.loads(s)['cardinality']
100000 loops, best of 3: 5.73 µs per loop

因此,您应该使用json,因为它相对比ast更快