【问题标题】:Syntax error when defining time with colon用冒号定义时间时出现语法错误
【发布时间】:2015-02-04 03:49:18
【问题描述】:

我无法终生纠正这个错误,当我运行这个脚本时,它给了我一个语法错误。

def extract_hours(tm:'hours:minutes'):
    """returns an integer representing the number of hours number, number -> number"""
    return int(tm.split(':')[0])

有人可以帮帮我吗?

【问题讨论】:

  • 你能发布你的语法错误吗?
  • 您希望语法tm:'hours:minutes' 做什么?
  • @BrenBarn 我不知道 tm: 部分,这正是我被告知要做的。我需要用冒号定义时间,而当我运行脚本时这不起作用。
  • 函数注释(tm:'hours:minutes' 中第一个冒号后面的部分)在 Python 2 中不受支持 - 您使用的是 Python 3.something 吗?
  • 运行脚本时,您是否在时间上加上引号 - extract_hours("1:13")extract_hours(1:13)

标签: python python-3.x annotations


【解决方案1】:

只需将字符串传递给您的函数:

def extract_hours(tm:'hours:minutes'):
    """returns an integer representing the number of hours number, number -> number"""
    return int(tm.split(':')[0])

然后这样称呼它:

extract_hours('1:13')

【讨论】:

  • 我需要它看起来像这样以适应约束:def extract_hours(tm:'hours:minutes'):
  • 你是这样称呼的吗? extract_hours('1:13') 作为字符串?
  • tm:'hours:minutes'是python 3函数注解。
  • @levi 谢谢没有意识到这一点。但是,它不应该真正改变行为,对吧? (如果你调用正确的话)
  • @JBaczuk 是的。就是这样。
【解决方案2】:

你能用字符串调用函数吗

def extract_hours(tm:'hours:minutes'):
    """returns an integer representing the number of hours number,    number -> number"""
    return int(tm.split(':')[0])

调用函数:

>>> extract_hours("12:34")
    12
>>> 

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多