简体   繁体   English

从 python 字符串中获取特定部分

[英]Getting a specific part from a python string

In Geopy, whenever I print the location for example在 Geopy 中,每当我打印位置时,例如

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?我怎样才能做到这一点?

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])

You can use split(splitString) function, it will split your string at the possitions where it finds the defined splitString .您可以使用split(splitString) function,它会在找到定义的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.请注意,我使用了“,”,而不是“,”,因此您的结果字符串中不会有空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM