2

In Geopy, whenever I print the location for example

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="TTT")
location = geolocator.geocode("Washington")
print(location.raw)

I get the result like this --> Washington, District of Columbia, United States

What I want is to print the country name which means everything after the last coma

How can I do this?

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
Armaghan
  • 21
  • 3
  • you can use split(',') function which returns list of values from it you can extract the last value see split() function and try!! – Bhavya Parikh Apr 20 '21 at 13:00

3 Answers3

2

You can use split(splitString) function, it will split your string at the possitions where it finds the defined splitString.

In your case it could be:

str = "Washington, District of Columbia, United States"
country = str.split(", ")[-1]

Note that I used ", ", not "," so you won't have a space in your resulting string.

chillking
  • 311
  • 1
  • 9
1

One easy way:

s = "Washington, District of Columbia, United States"
print(s.split(",")[-1].strip())
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
1
from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="TTT")
location = geolocator.geocode("Washington")
print(location.raw.split(",")[-1])
Masmoudi
  • 123
  • 1
  • 9