Home > database >  Python list with type strings
Python list with type strings

Time:11-21

I have got a python list

Year= [‘1997JAN’, ‘1997FEB’, ‘1997MAR’‘1997APR’………………………’2021SEP’’2021OCT’]

I would like to extract only years from the above list but not the months

How can I extract only years?

Year = [1997,1997,1997,…………………2021,2021]

CodePudding user response:

If you have these dates:

dates = ['1997JAN', '1997FEB', '1997MAR','1997APR', '2022NOV']

Just use this to extract years from dates:

years = [x[0:4] for x in dates]

CodePudding user response:

You import and use the module re:

import re

Year= ['1997JAN', '1997FEB', '1997MAR','1997APR','2021SEP','2021OCT']

Years_only=[re.findall(r'\d ', year)[0] for year in Year]

Years_only

Output

['1997', '1997', '1997', '1997', '2021', '2021']

CodePudding user response:

You can first extract the numbers with filter and str.isdigit like this:

input = '1997JAN'
output = ''.join(filter(str.isdigit, input))
print(output)
# '1997' (This is still string)

Now we should cast it to integer:

output = int(''.join(filter(str.isdigit, input)))
print(output)
# 1997

You can do this in all elements in the list with map:

output = list(map(lambda input: int(''.join(filter(str.isdigit, input))), Year))
print(output)
# [1997,1997,1997,…………………2021,2021]
  • Related