问题
编写一个函数,将形如 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