maikati
maikati

Reputation: 61

Python splitting values from urllib in string

I'm trying to get IP location and other stuff from ipinfodb.com, but I'm stuck.

I want to split all of the values into new strings that I can format how I want later. What I wrote so far is:

resp = urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=mykey&ip=someip').read()
    out = resp.replace(";", " ")
    print out

Before I replaced the string into new one the output was:

OK;;someip;somecountry;somecountrycode;somecity;somecity;-;42.1975;23.3342;+05:00

So I made it show only

OK someip somecountry somecountrycode somecity somecity - 42.1975;23.3342 +05:00

But the problem is that this is pretty stupid, because I want to use them not in one string, but in more, because what I do now is print out and it outputs this, I want to change it like print country, print city and it outputs the country,city etc. I tried checking in their site, there's some class for that but it's for different api version so I can't use it (v2, mine is v3). Does anyone have an idea how to do that?

PS. Sorry if the answer is obvious or I'm mistaken, I'm new with Python :s

Upvotes: 0

Views: 586

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

You need to split the resp text by ;:

out = resp.split(';')

Now out is a list of values instead, use indexes to access various items:

print 'Country: {}'.format(out[3])

Alternatively, add format=json to your query string and receive a JSON response from that API:

import json

resp = urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?format=json&key=mykey&ip=someip')
data = json.load(resp)

print data['countryName']

Upvotes: 1

Related Questions