从 python 中 space 之后的最后一个实例的字符串中提取子字符串

Extracting a substring from string that is the last instance after a space in python

我不熟悉 python 字符串操作。 我有一个格式相似的字符串集合,字符串的两个示例如下,ex1:​​“2015 年毕业”,ex2:“2022 年毕业”。我想提取的这些字符串部分是年份,即最后一个没有空格的字符串。使用上面的示例,我希望输出类似“2015”和“2020”的内容,并将它们保存到列表中。有没有办法使用此条件提取子字符串并将其保存到列表中?

视觉上这就是我想要的

str1<-"Graduated in 2015" 
str2<-"Graduates in 2022"
#some code extracting the year substring and adding them to a list l
print(l)
['2015','2022']


list_of_strings = ["Graduated in 2015", "Graduates in 2022"]

l = [s.split()[-1] for s in list_of_strings]

print(l)  # ['2015', '2022']

如果它处于固定模式,您可以拆分并使用负索引:

str1 = "Graduated in 2015" 
str2 = "Graduates in 2022"
print([int(str1.split()[-1]),int(str2.split()[-1])])