Getting a specific part from a python string

Viewed 62

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?

3 Answers

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.

One easy way:

s = "Washington, District of Columbia, United States"
print(s.split(",")[-1].strip())
from geopy.geocoders import Nominatim

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