提问人:rorycostigan 提问时间:10/31/2023 最后编辑:C.Nivsrorycostigan 更新时间:10/31/2023 访问量:63
如何将列表中的一个单数字符串转换为整数
How do I covert one singular string in a list to an integer
问:
尝试将 12 小时时钟转换为 24 小时时钟。输入 = 晚上 11:00,输出应为 23:00。 我知道在下午时间我必须加 12,但要做到这一点,我需要将数字从字符串转换为整数。
hr24 = list(input().split(“ “))
hr24[0] = int(hr24[0])
和
hr24 = list(input().split(“ “))
hr24[0] = map(int, hr24[0])
两者都会导致错误,谁能帮忙?
答:
0赞
addem
10/31/2023
#1
# store input in a string
input_str = input()
# split the input string at the space, store time and period
time, period = input_str.split(' ')
res = input_str
if period == 'PM':
# split time at ':', store hour and minutes
hour, minutes = time.split(':')
# convert hour to int add 12 and convert back to string
res = str(int(hour) + 12) + ':' + minutes
print(res)
评论
0赞
Jeremy Caney
10/31/2023
感谢您对 Stack Overflow 社区的贡献。这可能是一个正确的答案,但提供代码的额外解释,以便开发人员能够理解你的推理,这将是非常有用的。这对于不熟悉语法或难以理解概念的新开发人员特别有用。为了社区的利益,您能否编辑您的答案以包含其他详细信息?
2赞
Mark Tolonen
10/31/2023
#2
使用 datetime
模块解析时间并根据需要显示它:
import datetime as dt
t = '11:00 PM'
d = dt.datetime.strptime(t, '%I:%M %p')
h24 = d.strftime('%H:%M')
print(h24) # 23:00
评论
input.split