Jupyter Notebook 中的代码不是 Python 2.7.18 中的 运行

Code in Jupyter Notebook is not running in Python 2.7.18

我在 Jupyter Notebook 上写了一个 运行ning 函数。现在我想 运行 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}")

使用 format 代替 f-stringpython 3.6+ 中工作:

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

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

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

f 字符串仅 运行s 在 Python 3.6+ 上。如果你真的需要 运行 on Python 2.7.18 也许你需要改变你的字符串使用 .format 或使用 % operator

而不是

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

使用

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

或年龄最大的

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