python - 在 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,必须进行哪些更改?
解决方案
在我复制并粘贴错误消息的那一刻,我意识到导致错误消息的原因f'{value}'
一定是在 Python 版本 2.7.6 中不存在使用类似代码格式化字符串的想法,并切换到使用类似代码'{}'.format(value)
是必需的。我试过这个,代码在 Python 2.7.6 中是成功的。
推荐阅读
- javascript - 如何使用 jQuery 或 javascript 修改 URL 的结尾?
- arrays - Angular - 数组 forEach 索引
- ios - iOS - 将证书添加到受信任的证书
- amazon-web-services - Cognito paswordless auth via link
- r - position_stack 和堆叠条形图中百分比标签的反转
- python-3.x - BeautifulSoup .find() 捕获太多文本(如何缩小范围?)
- python-3.x - 如何从维基百科页面标题中获取页面 id
- microservices - 微服务数据库设计问题
- python - 如何使用python中的max函数获取变量的名称而不是变量中的数字
- javascript - 使用麦克风输入降低 Web 音频频谱分析仪的采样率