Python list with type strings

Question:

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]
Asked By: swin cine

||

Answers:

If you have these dates:

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

Just use this to extract years from dates:

years = [int(x[:4]) for x in dates]
Answered By: here_need_help

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']
Answered By: Khaled DELLAL

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]
Answered By: Ali
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.