I have to parse a list of simple strings with a known structure but I'm finding it unnecessarily clunky. I feel I'm missing a trick, perhaps some simple regex that would make this trivial?
The string refers to some number of years/months in the future, I want to make this into decimal years.
Generic format: "aYbM"
Where a is the number of years, b is the number of months these can be ints and both are optional (along with their identifier)
Test cases:
5Y3M == 5.25
5Y == 5.0
6M == 0.5
10Y11M = 10.91666..
3Y14M = raise ValueError("string '%s' cannot be parsed" %input_string)
My attempts so far have involved string splitting and been pretty cumbersome though they do produce the correct results:
def parse_aYbM(maturity_code):
maturity = 0
if "Y" in maturity_code:
maturity += float(maturity_code.split("Y")[0])
if "M" in maturity_code:
maturity += float(maturity_code.split("Y")[1].split("M")[0]) / 12
return maturity
elif "M" in maturity_code:
return float(maturity_code[:-1]) / 12
else:
return 0