简体   繁体   English

如何从 python 中的 api 响应中提取特定字符串?

[英]how to extract specific string from api response in python?

how to extract "e2f64fd6-13aa-5c6c-932a-c366a4f56076" from the below api response in python?如何从 python 中的以下 api 响应中提取“e2f64fd6-13aa-5c6c-932a-c366a4f56076”?

{"message": "Rendition service output e2f64fd6-13aa-5c6c-932a-c366a4f56076/ae8f5aae-4d6a-5a17-9f95-d918634a668c has been created successfully."} {"message": "渲染服务 output e2f64fd6-13aa-5c6c-932a-c366a4f56076/ae8f5aae-4d6a-5a17-9f95-d918634a668c 已成功创建。"}

Assuming the message follows the same format always, there are several ways: First I save the message on a variable d so I can work with it:假设消息始终遵循相同的格式,有几种方法:首先,我将消息保存在变量d中,以便可以使用它:

d = {"message": "Rendition service output e2f64fd6-13aa-5c6c-932a-c366a4f56076/ae8f5aae-4d6a-5a17-9f95-d918634a668c has been created successfully."}

Solution 1:解决方案1:

d['message'][25:].split('/')[0]
'e2f64fd6-13aa-5c6c-932a-c366a4f56076'

Solution 2 (I like this one more):解决方案2(我更喜欢这个):

d['message'].split(' ')[3].split('/')[0]
'e2f64fd6-13aa-5c6c-932a-c366a4f56076'

If the format of the API response is fixed, you can use regex to extract your data.如果 API 响应的格式是固定的,您可以使用正则表达式来提取数据。

import regex

message = "Rendition service output e2f64fd6-13aa-5c6c-932a-c366a4f56076/ae8f5aae-4d6a-5a17-9f95-d918634a668c has been created successfully."

m = regex.search('output (.+?)/', message)

if m:
    print(m.group(1))
    # prints e2f64fd6-13aa-5c6c-932a-c366a4f56076

If you don't want to use regex you could do:如果您不想使用正则表达式,您可以这样做:

start = message.find('output ') + len('output ') # To get the index of the character behind this string
end = message.find('/', start)
print(message[start:end])
# prints e2f64fd6-13aa-5c6c-932a-c366a4f56076

Found the information here这里找到信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM