Say you have the following string
values:
str_one = '03H 49m 06s'
str_two = '18m 23s'
str_three = '56s'
How could these strings be converted to int
such that the output is as follows (correspondingly)?
13746
1103
56
After some thought, the only thing I could think of was to create a custom function called from_str_to_seconds
that takes as input a string of the form:
00H 00m 00s
00m 00s
00s
From these strings, from_str_to_seconds
function takes the specific slices that contain the numbers, then converts those numbers to integers which are then multiplied by their equivalent converter, and finally sum them all together to return the net number of seconds:
def from_str_to_seconds(string: str):
if 'H' not in string:
if 'm' not in string:
seconds = int(string[:-1])
return seconds
else:
seconds = (int(string[:2])*60)+int(string[-3:-1])
return seconds
else:
seconds = (int(string[:2])*3600)+(int(string[-7:-5])*60)+int(string[-3:-1])
return seconds
from_str_to_seconds('03H 49m 06s')
Out[2]: 13746
from_str_to_seconds('18m 23s')
Out[3]: 1103
from_str_to_seconds('56s')
Out[4]: 56
One solution is using re
:
import re
strs = ["03H 49m 06s", "18m 23s", "56s", "1h"]
pat = re.compile(
r"(?:(\d+)\s*h)?(?:\s*(\d+)\s*m)?(?:\s*(\d+)\s*s)?", flags=re.I
)
for st in strs:
h, m, s = (0 if v is None else int(v) for v in pat.search(st).groups())
print("{:<13} {}".format(st, h * 60 * 60 + m * 60 + s))
Prints:
03H 49m 06s 13746
18m 23s 1103
56s 56
1h 3600