简体   繁体   中英

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?

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

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 = {"message": "Rendition service output e2f64fd6-13aa-5c6c-932a-c366a4f56076/ae8f5aae-4d6a-5a17-9f95-d918634a668c has been created successfully."}

Solution 1:

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

Solution 2 (I like this one more):

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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