简体   繁体   中英

Return particular string from response

I am trying to return a particular string value after getting response from request URL. Ex. response =

{
    'assets': [
    {
        'VEG': True,
        'CONTACT': '12345',
        'CLASS': 'SIX',
        'ROLLNO': 'A101',
        'CITY': 'CHANDI',
    }
    ],
    "body": "**Trip**: 2017\r\n** Date**: 15th Jan 2015\r\n**Count**: 501\r\n\r\n"
    }

This is the response which i am getting, from this I need only Date: 15th Jan 2015 . I am not sure how to do it.

Any help would be appreciated.

assuming it is a dictionary

a={'body': '**Trip**: 2017\\r\\n** Date**: 15th Jan 2015\\r\\n**Count**: 501\\r\\n\\r\\n', 'assets': [{'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI'}]}

then

required=a['body'].split('\r\n')[1].replace('**','')
print required

result:

' Date: 15th Jan 2015'
  1. Access the key body of the dictionary a

  2. split through \\r\\n to get a list ['**Trip**: 2017', '** Date**: 15th Jan 2015', '**Count**: 501', '', '']

  3. access it's first index and replace ** with empty('')

a = str(yourdictionary)
print([e for e in a.split("\r\n") if "Date" in e][0].remove("**").strip())

Try this

>>> body = response['body']
>>> bodylist = body.split('\r\n')
>>> for value in bodylist:
...     value = value.split(':')
...
>>> for i,value in enumerate(bodylist):
...     bodylist[i] = value.split(':')
...
>>> for i, value in enumerate(bodylist):
...     if bodylist[i][0] == '** Date**':
...             print(bodylist[i][1])
...
 15th Jan 2015

I have trown it in the interpreter and this works. I don't know if it is the best code around, but it works ;-)

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