0

I am new to python manipulation of strings. I have a collection of strings that have a similar format, two examples of the strings are as follows, ex1: "Graduated in 2015", ex2: "Graduates in 2022". The portion of these strings that I would like to extract are the years that is the string that is the last string without spaces. Using the above examples I would like to have an output of something like '2015' and '2020' and save these to a list. Is there a way to extract a substring using this criteria and save these to a list?

visually this is what I want

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


2 Answers2

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

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

print(l)  # ['2015', '2022']
Joonyoung Park
  • 474
  • 3
  • 6
0

If it is in a fixed pattern you can split and use negative indexing:

str1 = "Graduated in 2015" 
str2 = "Graduates in 2022"
print([int(str1.split()[-1]),int(str2.split()[-1])])
Wasif
  • 14,755
  • 3
  • 14
  • 34