对于一个类,我必须编写一个函数,它采用03:12:19的形式(换句话说,3小时、12分钟和19秒)并将它们转换为相应的秒数。我已经开始了,但似乎无法使数学工作,下面是我目前的代码:
def secs(timestr):
import re
timexp = re.compile('(\d\d):(\d\d):(\d\d)')
calc = re.sub(timexp,r'int(\1)*3600+int(\2*60)+int(\3)',timestr)
return print(calc)
str = '03:20:13'
secs(str)
我已经把r去掉了,但结果很奇怪。帮忙吗?在
regexp对于解析输入字符串来说可能是太过了,而对于计算总秒数,regexp是完全错误的工具。这里有一个简单的替代品:
这不处理错误检查(不是正确数量的“:”分隔符、非数字内容等),但是原始的regexp方法也不处理。如果您确实需要检查输入,我会这样做:
^{pr2}$还有其他方法。在
如果您想要一个字符串而不是整数表示秒数,
return str(int(hours) * 3600 + int(minutes) * 60 + int(seconds))
。在编辑:针对“我被指示使用regexp替换来完成此操作,因此我必须这样做”:
re.sub可以接受两种不同类型的替换参数。可以提供字符串模式或函数来计算替换字符串。字符串模式不做数学运算,所以必须使用函数。在
但这是一种糟糕的方法,除非您试图在单个较大的字符串中转换这些时间模式的多次出现。在
在这里,编译regexp不是真正必要的,甚至没有帮助,因为每次调用函数时都要重新编译。通常的方法是在函数外部编译它,但正如regexp docs注意:
不过,这是个好习惯。只是不在像这样的局部函数定义中。在
另一个选择是尝试切片。(以下是关于切片表示法的一些信息:Explain Python's slice notation)
如果传递给函数的时间总是以相同的格式(即hh:mm:ss),则切片将允许您分离时间的每个组成部分。对字符串进行切片仍然会返回一个字符串,因此对每个时间切片组件都使用int()。secs函数看起来像这样:
你在用re.sub公司,它将正则表达式匹配替换为第二个参数。在
相反,你应该跑重新匹配(timexp,timestr)获取匹配对象。此对象具有用于访问组的API(正则表达式的圆括号部分):匹配组(0)是整个字符串,匹配组(1) 是第一个两位数的块,匹配组(2) 是第二个。。。在
你可以从那里处理内存中的数字。在
相关问题 更多 >
编程相关推荐