在特定字符串和字符集

时间:2017-12-05 06:30:57

标签: python sql regex string split

我是一个python noob,我在尝试提取数字时遇到了麻烦。它是一个SQL查询,但我把它变成了一个字符串类型。如果有更好的方法,请告诉我。我的字符串包含许多相似的单词,所以我想在一组不同的单词后提取数字。

实施例

{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}

出于这一点,我想提取" 37"从他们的关键" id"。将其存储在变量

我尝试使用.split(),但我不确定是否有效,因为有些字符由于撇号和冒号而无法使用索引。我知道有一种方法可以使用SQL来获取结果(query.get(' id')),但我想知道一种在字符串中提取它的方法。

请帮忙!谢谢!

2 个答案:

答案 0 :(得分:1)

这看起来像dictionary - 因此您可以通过set["id"]

轻松访问它
di = {'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}

print(di["id"])

输出:

37

完成。

如果它是一个字符串,你可以把它分成这样的字典:

di = "{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}"

pairs = [x.replace("'","").strip("{}") for x in di.split(",")]
dic = dict( [ x.replace("'","").strip().split(":",1) for x in pairs] )
print(dic)
print(dic ["id"])

输出:

{'first_name': ' Abigail', 'last_name': ' Smith', 'updated': ' 2017-12-04 22:12:24.699-08', 'account_id': ' 338502', 'created': ' 2017-12-04 22:12:24.699-08', 'student_id': ' 1730', 'notes': '', 'school_id': ' 16', 'major_id': ' 20', 'status': ' OPEN', 'id': ' 37'}
 37

答案 1 :(得分:1)

您可以使用ast模块将字符串转换为字典

import ast
d="{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}"
dic=ast.literal_eval(d)
print dic['id']

输出

37