首页 > 解决方案 > 在 Python 2.7.6 中返回格式化列表的语法无效

问题描述

我用 Python 3.7 编写了一个不能在 Python 2.7.6 中运行的程序。该程序旨在将秒分解为秒、分钟、小时、天和年。代码的这个特定部分发生了问题:

return f' {remainder} {metric}' + ('s,' if remainder != 1 else ','), int(val / metric_val)  # returns 'second' or 'seconds' as well as a new 'current_time', rounded down

当我尝试运行它时,我收到了这个错误:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from solution import *
  File "/home/codewarrior/solution.py", line 24
    return f' {remainder} {metric}' + ('s,' if remainder != 1 else ','), int(val / metric_val)
                                  ^
SyntaxError: invalid syntax

要使此代码适用于 2.7.6,必须进行哪些更改?

标签: pythontime

解决方案


在我复制并粘贴错误消息的那一刻,我意识到导致错误消息的原因f'{value}'一定是在 Python 版本 2.7.6 中不存在使用类似代码格式化字符串的想法,并切换到使用类似代码'{}'.format(value)是必需的。我试过这个,代码在 Python 2.7.6 中是成功的。


推荐阅读