假设您有以下内容
string
值:
str_one = '03H 49m 06s'
str_two = '18m 23s'
str_three = '56s'
如何将这些字符串转换为
int
使得输出如下(相应地)?
13746
1103
56
更新,我找到了自己的答案
经过思考,我唯一能想到的就是创建一个名为
from_str_to_seconds
其采用以下形式的字符串作为输入:
-
00H 00m 00s
-
00m 00s
-
00s
从这些串中,
从_str_to_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