Regexps are probably overkill for parsing the input string, and entirely the wrong tool for calculating the total number of seconds. Here's a simple replacement:
def secs(timestr):
hours, minutes, seconds = timestr.split(':')
return int(hours) * 3600 + int(minutes) * 60 + int(seconds)
This doesn't handle error checking (not the right number of ':' dividers, non-digit contents, etc) but then neither does your original regexp approach. If you do need to sanity check the input, I'd do it like this:
def secs(timestr):
timeparts = timestr.split(':')
if len(timeparts) == 3 and all((part.isdigit() for part in timeparts)):
return int(timeparts[0]) * 3600 + int(timeparts[1] * 60 + int(timeparts[2])
else:
# not a matching string - do whatever you like.
return None
There are other approaches.
If you want a string rather than integer for the number of seconds, return str(int(hours) * 3600 + int(minutes) * 60 + int(seconds))
.
Edit: in response to " i was instructed to do this with a regexp substitution so that is what i must do":
re.sub can take two different kinds of replacement arguments. You can either provide a string pattern or a function to calculate the replacement string. String patterns do not do math, so you must use a function.
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
def _calculate_seconds(timematch):
return str(int(timematch.group(1)) * 3600 + int(timematch.group(2)) * 60 + int(timematch.group(3)))
def secs(timestr):
timexp = re.compile(r'(\d{1,2}):(\d{1,2}):(\d{1,2})')
return re.sub(timexp, _calculate_seconds, timestr)
But this is a bad approach unless you're trying to convert multiple occurrences of these time patterns in a single larger string.
Compiling the regexp isn't really necessary or even helpful here, since you redo it each time you call the function. The usual approach is to compile it outside the function - but as the regexp docs note:
The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.
Still, it's a good habit to get into. Just not inside the local function definition like this.