【问题标题】:Can you please tell whats wrong with this你能告诉我这有什么问题吗
【发布时间】:2020-04-27 18:23:57
【问题描述】:

**你能告诉我这个错误有什么问题吗?***************

codio@random-media:~/workspace$ python final.py
File "final.py", line 4
  return f'print("{phrase}")\n'
                            ^
SyntaxError: invalid syntax


def createOutput(lang, phrase):
    if lang == "python":
        return f'print("{phrase}")\n'
    if lang == "c++":
        return f'cout << "{phrase}\\n";\n'
    if lang == "c":
        return f'printf("{phrase}\\n");\n'
    return ""

【问题讨论】:

  • 即使在语法上有效的 Python 版本上,编写它也没有任何意义。
  • 请发帖minimal reproducible example。仅使用回溯很难推断出问题。
  • 你使用的是python2?
  • 当解析器发现语法错误但问题可能出在上面一两行时,Python 会报告。发布更多导致此错误的代码,以便我们查看。
  • 我更新了缩进。让我知道它是否正确。在使用 python 2 时,这很可能是 python 3 语法的问题。将版本添加到问题中以便我们知道。

标签: python syntax


【解决方案1】:

python2 不支持 F 字符串。

使用格式

'print("{}")\n'.format(var)

或者使用 Python 3.6+ 并运行代码

【讨论】:

  • 我使用了 Codio 在线编译器
  • 查看python版本
  • def createOutput(lang, phrase): if lang == "python": return f'print("{phrase}")\n' if lang == "c++": return f'cout
  • @arby - 你能把它放在原始问题的代码块中,就像你发布的语法错误一样,以便我们更清楚地看到它吗?
  • 你能去掉“f”字符串并使用格式吗?请尝试