【发布时间】:2015-07-05 01:32:19
【问题描述】:
我必须解析具有已知结构的简单字符串列表,但我发现它不必要地笨重。 我觉得我错过了一个技巧,也许是一些简单的正则表达式会让这变得微不足道?
这个字符串是指未来的若干年/月,我想把它变成小数年。
通用格式:“aYbM”
其中 a 是年数,b 是月数,它们可以是整数,并且都是可选的(连同它们的标识符)
测试用例:
5Y3M == 5.25
5Y == 5.0
6M == 0.5
10Y11M = 10.91666..
3Y14M = raise ValueError("string '%s' cannot be parsed" %input_string)
到目前为止,我的尝试涉及字符串拆分,尽管它们确实产生了正确的结果,但非常麻烦:
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
【问题讨论】: