如何删除字符串

2024-10-05 10:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这样的api响应。你知道吗

'(\'37.2 mi\', \'{\\n   "destination_addresses" : [ "Pimpri-Chinchwad, Maharashtra, India" ],\\n   "origin_addresses" : [ "Ranjangaon, Maharashtra, India" ],\\n   "rows" : [\\n      {\\n         "elements" : [\\n            {\\n               "distance" : {\\n                  "text" : "37.2 mi",\\n                  "value" : 59925\\n               },\\n               "duration" : {\\n                  "text" : "1 hour 37 mins",\\n                  "value" : 5814\\n               },\\n               "status" : "OK"\\n            }\\n         ]\\n      }\\n   ],\\n   "status" : "OK"\\n}\\n\')'

我想删除这个..的单引号。。 即 预期输出应如下所示:

(\'37.2 mi\', \'{\\n   "destination_addresses" : [ "Pimpri-Chinchwad, Maharashtra, India" ],\\n   "origin_addresses" : [ "Ranjangaon, Maharashtra, India" ],\\n   "rows" : [\\n      {\\n         "elements" : [\\n            {\\n               "distance" : {\\n                  "text" : "37.2 mi",\\n                  "value" : 59925\\n               },\\n               "duration" : {\\n                  "text" : "1 hour 37 mins",\\n                  "value" : 5814\\n               },\\n               "status" : "OK"\\n            }\\n         ]\\n      }\\n   ],\\n   "status" : "OK"\\n}\\n\')

在Python中如何做到这一点?你知道吗


Tags: textvalueaddressesstatusokelementsorigindestination
2条回答

使用python的ast包来评估所需文本的实际形式。 假设您的字符串,下面可能是适合您需求的解决方案。你知道吗

import ast
original_value = '(\'37.2 mi\', \'{\\n   "destination_addresses" : [ "Pimpri-Chinchwad, Maharashtra, India" ],\\n   "origin_addresses" : [ "Ranjangaon, Maharashtra, India" ],\\n   "rows" : [\\n      {\\n         "elements" : [\\n            {\\n               "distance" : {\\n                  "text" : "37.2 mi",\\n                  "value" : 59925\\n               },\\n               "duration" : {\\n                  "text" : "1 hour 37 mins",\\n                  "value" : 5814\\n               },\\n               "status" : "OK"\\n            }\\n         ]\\n      }\\n   ],\\n   "status" : "OK"\\n}\\n\')'
formatted_value = ast.literal_eval(original_value)
print(formatted_value)

这将输出为-

('37.2 mi', '{\n "destination_addresses" : [ "Pimpri-Chinchwad, Maharashtra, India" ],\n "origin_addresses" : [ "Ranjangaon, Maharashtra, India" ],\n "rows" : [\n {\n "elements" : [\n {\n "distance" : {\n
"text" : "37.2 mi",\n "value" : 59925\n
},\n "duration" : {\n "text" : "1 hour 37 mins",\n "value" : 5814\n },\n
"status" : "OK"\n }\n ]\n }\n ],\n
"status" : "OK"\n}\n')

如果您的响应存储在类似response= "1 response text 2"的字符串中,并且希望删除字符串的第一个和最后一个字符 e、 g

response = "1 response text 2" 
response = string[1:-1]

If将删除1和2

输出

  response text 

相关问题 更多 >

    热门问题