-3

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

Update, I found my own answer

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:

  1. 00H 00m 00s
  2. 00m 00s
  3. 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

Tests

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
NoahVerner
  • 937
  • 2
  • 9
  • 24
  • You should probably be using timedelta, not int, but that won't help with this particular problem. – Jasen Oct 19 '22 at 00:11
  • 1
    a couple of ways to do this.. 1) lowercase string, then parse out the ```h```, ```m```, and ```s``` values. change to int. 2) use regex. then change parameters to int. – ewokx Oct 19 '22 at 00:14

1 Answers1

1

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Thank you for providing another interesting solution to my problem, I will mark it as the right one because I learned something new (Although I didn't understand it at all) – NoahVerner Oct 19 '22 at 21:08