def parse_aYbM(text):
    a, b = re.match('(?:(\\d+)Y)?(?:(\\d+)M)?', text).groups()
if a == b == None:
    raise ValueError('input does not match aYbM')
a, b = [(int(item) if item is not None else 0) for item in (a, b)]
return a + b / 12.0
tests = [('5Y3M', 5.25), ('5Y', 5.0), ('6M', 0.5), ('10Y11M', 10.917), (
    '3Y14M', 4.167)]
for test, expected in tests:
    result = parse_aYbM(test)
status = 'Failed'
if abs(result - expected) < 0.001:
    status = 'Passed'
print('{}: {} --> {}'.format(status, test, result))
Python - Parse string, known structure