如何从字符串中删除 ('')

How to remove ('') from string

我正在编写代码以使用 IP 地理定位获取地理定位信息 API。我在我的 jupyter notebook 中使用了以下代码...

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

ip = '8.8.8.8'
api_key = 'your_api_key'
api_url = 'https://geo.ipify.org/api/v1?'

url = api_url + 'apiKey=' + api_key + '&ipAddress=' + ip
result = urlopen(url).read().decode('utf8')
print(result)

我得到了以下结果,但是 returns 以下字符串...

'{"ip":"8.8.8.8","location":{"country":"US","region":"California","city":"Mountain View","lat":37.4223,"lng":-122.085,"postalCode":"94043","timezone":"-07:00","geonameId":5375480},"domains":["0--9.ru","000.lyxhwy.xyz","000180.top","00049ok.com","001998.com.he2.aqb.so"],"as":{"asn":15169,"name":"Google LLC","route":"8.8.8.0\/24","domain":"https:\/\/about.google\/intl\/en\/","type":"Content"},"isp":"Google LLC"}'

我正在尝试删除开头和结尾的字符串。我尝试通过对结果变量调用列表函数来将此字符串更改为列表,但这没有用。我想获得以下输出...

{"ip":"8.8.8.8","location":{"country":"US","region":"California","city":"Mountain View","lat":37.4223,"lng":-122.085,"postalCode":"94043","timezone":"-07:00","geonameId":5375480},"domains":["0--9.ru","000.lyxhwy.xyz","000180.top","00049ok.com","001998.com.he2.aqb.so"],"as":{"asn":15169,"name":"Google LLC","route":"8.8.8.0\/24","domain":"https:\/\/about.google\/intl\/en\/","type":"Content"},"isp":"Google LLC"}

通过这样做,我将得到一本字典,我可以使用各种键来处理它。任何帮助将不胜感激。

如果你想要一本字典,你不应该试图删除引号,因为它表示一个 string 变量。您应该改为使用 JSON,因为这是一个有效的 JSON 字符串:

import json
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

ip = '8.8.8.8'
api_key = 'your_api_key'
api_url = 'https://geo.ipify.org/api/v1?'

url = api_url + 'apiKey=' + api_key + '&ipAddress=' + ip

result = json.loads(urlopen(url).read().decode('utf8'))
print(result)

这将为您提供所需的词典。

您可以使用 json library.

import json
str = '{"ip": "8.8.8.8"}'
res = json.loads(str)
print(res)

结果将是字典。