【问题标题】:Code in Jupyter Notebook is not running in Python 2.7.18Jupyter Notebook 中的代码未在 Python 2.7.18 中运行
【发布时间】:2020-11-16 13:10:07
【问题描述】:

我编写了一个在 Jupyter Notebook 上运行的函数。现在我想在 Python 2.7.18 中运行相同的代码,但在“”部分出现语法错误..

import datetime
now = datetime.datetime.now()
i = now.year
j = now.month
k = now.day
def concat(i, j):
    return eval(f"{i}{j}{k}")

【问题讨论】:

  • 您为什么要使用 Python 2? Python 2 已于今年结束。
  • 为什么要在 python 2.7 中运行新的东西?
  • 在 Py3.6 之前不支持 f 字符串。
  • 原因与问题无关。我没有问原因
  • 那么请注意,Python 2 和 Python 3 之间还有很多其他变化,例如 printinputrange 的行为。你必须解决这些问题。

标签: python pandas python-2.7


【解决方案1】:

使用format 替代f-strings 在python 3.6+ 工作:

def concat(i, j):
    return eval("{}{}{}".format(i, j, k))

【讨论】:

  • 还有一个第三方包future-fstrings是fstrings到python的反向移植
【解决方案2】:

您在 python2 中使用了 f-strings,但此功能是在 python3.6 中引入的
return eval(f"{i}{j}{k}")

可以正常格式化输出,也可以使用python 2的f-string模拟器包:https://pypi.org/project/fstrings/

【讨论】:

    【解决方案3】:

    f 字符串仅在 Python 3.6+ 上运行。如果您真的需要在 Python 2.7.18 上运行,您可能需要更改字符串使用 .format 或使用 % 运算符

    而不是

    eval(f"{i}{j}{k}")

    使用

    eval("{0}{1}{2}".format(i,j,k))

    或最老的

    eval("%s %s %s" % (i, j ,k)")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多