将形如 5D, 30s 的字符串转为秒

问题

编写一个函数,将形如 5D, 30s, 的字符串转为秒‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬

========= ======= ===================
Character Meaning Example
========= ======= ===================
s Seconds ‘60s’ -> 60 Seconds
m Minutes ‘5m’ -> 5 Minutes
h Hours ‘24h’ -> 24 Hours
d Days ‘7d’ -> 7 Days
========= ======= ===================

模板代码

def convert_to_seconds(time_str):
    # write code here

while True:
    line = sys.stdin.readline()
    line = line.strip()
    if line == '':
        break
    print(convert_to_seconds(line))

解答代码:

import sys

def convert_to_seconds(time_str):
    time_str = time_str.lower()
    if time_str[-1] == 'd':
        timesingle = float(time_str[:-1])*24*60*60
    elif time_str[-1] == 'h':
        timesingle = float(time_str[:-1])*60*60
    elif time_str[-1] == 'm':
        timesingle = float(time_str[:-1])*60
    elif time_str[-1] == 's':
        timesingle = float(time_str[:-1])
    return timesingle

while True:
    line = sys.stdin.readline()
    line = line.strip()
    if line == '':
        break
    print(convert_to_seconds(line))

里面使用sys.stdin.readline()可以实现标准输入,需要调用sys库,sys.stdin是一个标准化输入的方法,其中默认输入的格式是字符串

最开始我以为需要加个循环,结果一直在循环里出现各种错误,后来仔细找了一下,发现while True语法已经实现了循环,而sys.stdin.readline()每次只读一行。
出现TypeError: ‘int’ object is not subscriptable,由于自己在定义变量的时候定义重复了。
出现ValueError: invalid literal for int() with base 10: ’ ‘,值异常:以10为基数的int()的无效文字:’ ‘,int(’’)就是因为之前的循环带入了空字符。

题目来源:

https://python123.io/index/problem_set/pe/problems/13216

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值