简体   繁体   English

从响应中返回特定的字符串

[英]Return particular string from response

I am trying to return a particular string value after getting response from request URL. 我试图从请求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 . 这是我得到的回应,我只需要从此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 访问字典的键body

  2. split through \\r\\n to get a list ['**Trip**: 2017', '** Date**: 15th Jan 2015', '**Count**: 501', '', ''] 分隔\\r\\n以获取列表['**Trip**: 2017', '** Date**: 15th Jan 2015', '**Count**: 501', '', '']

  3. access it's first index and replace ** with empty('') 访问它的第一个索引并将**替换为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 ;-) 我不知道这是否是最好的代码,但是它有效;-)

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

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