'Find out total months from tenure which contains both years and month as string in python

I have a list which contains tenure let me show you -

['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mo']

Basically these are the all over tenure and thrown it into a lists what I need is basically from that lists is - 58, so total tenure is 58 in months

Any help will be appreciated



Solution 1:[1]

Using regex:

import re 

l = ['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mo']
total = 0
for i in l:
    m = re.search(r'(\d+)\s?mo(?:s)?', i) ## find digits before mo/mos
    m = m.group(1) if m else 0            ## m=0 if no matches
    y = re.search(r'(\d+)\s?yr(?:s)?', i) ## find digits before yr/yrs
    y = y.group(1) if y else 0            ## y=0 if no matches
    total += (int(m)+12*int(y))
print(total)

Result:

58

Solution 2:[2]

You can try and parse your list and addup your total months on specific keywords such as mos and yr.

Break down each item of your list into a list containing key words and values. Assuming the initial list is well formated :

list_ = ['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mos']
total = 0
for item in list_:
    string = item.split(' ')
    for i in range (len(string)):
        if string[i] == 'mos':
            total += int(string[i-1])
        if string[i] == 'yr':
            total += 12*int(string[i-1])

print(total)
# 58 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ytung-dev
Solution 2 Maxime Bouhadana