You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python时间转换代码优化:为输出添加首尾单引号

修复分钟转小时分钟格式的Python代码

原代码调用task8(61)时无法输出带首尾单引号的目标格式,直接修改代码即可解决问题:

修改后的代码

def task8(x):
    hours_total = x // 60
    minutes_total = x % 60
    
    # 处理分钟的单复数表述
    minutes_str = "minute" if minutes_total == 1 else "minutes"
    # 处理小时的单复数表述,保留格式需要的逗号
    hours_str = "hour," if hours_total == 1 else "hours,"
    
    # 拼接成带首尾单引号的目标字符串并输出
    result = f"'{hours_total} {hours_str} {minutes_total} {minutes_str}'"
    print(result)

task8(61)

修改说明

  • 用三元表达式简化了单复数判断逻辑,和原代码功能一致但更简洁
  • 通过f-string直接拼接出符合要求的完整字符串,首尾添加单引号
  • 调用task8(61)后会精准输出'1 hour, 1 minute'

内容的提问来源于stack exchange,提问作者Neo Motaung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:35:27