Py学习  »  Python

如何在Python3上将“03H 49m 06s”等字符串转换为秒(int类型)?[已关闭]

NoahVerner • 2 年前 • 1235 次点击  

假设您有以下内容 string 值:

str_one = '03H 49m 06s'
str_two = '18m 23s'
str_three = '56s'

如何将这些字符串转换为 int 使得输出如下(相应地)?

13746 
1103
56

更新,我找到了自己的答案

经过思考,我唯一能想到的就是创建一个名为 from_str_to_seconds 其采用以下形式的字符串作为输入:

  1. 00H 00m 00s
  2. 00m 00s
  3. 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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/158975
文章 [ 1 ]  |  最新文章 2 年前