我想将时间分隔符从法语方式转换为更标准的方式:


“ 17h30”变成“ 17:30”
“ 9h”变为“ 9:00”


使用regexp可以将17h30转换为17:30,但是我没有找到将9h转换为9:00的优雅方法

这是我到目前为止所做的:

import re
texts = ["17h30", "9h"]
hour_regex = r"(\d?\d)h(\d\d)?"
[re.sub(hour_regex, r"\1:\2", txt) for txt in texts]
>>> ['17:30', '9:']


我想做的是“如果\ 2不匹配,则写00”。

PS:当然,在匹配小时数时,我可以使用更详细的正则表达式,例如“([[12]?\ d)h [0123456] \ d”,但这不是重点。

最佳答案

有效地使用re.compile函数和or条件:

import re

texts = ["17h30", "9h"]
hour_regex = re.compile(r"(\d{1,2})h(\d\d)?")
res = [hour_regex.sub(lambda m: f'{m.group(1)}:{m.group(2) or "00"}', txt)
       for txt in texts]
print(res)   # ['17:30', '9:00']

07-24 17:15
查看更多