【问题标题】:SyntaxError: invalid syntax (when running python code from shell)SyntaxError:无效语法(从 shell 运行 python 代码时)
【发布时间】:2019-01-25 05:47:34
【问题描述】:

在 Jupyter Notebook 中,我的代码运行良好,但是当我从 shell 运行它时,我的这部分代码出现语法错误:

res = f'"x"'+" "+f'"y"'+" "+f'"t"'+" "+f'"id"'+" "+f'"id2"'
           ^
SyntaxError: invalid syntax

但是我需要字符串 res 看起来像:

""x" "y" "t" "id" "id2""

我猜是我创建它的方式导致了错误。

还有其他方法可以创建包含引号的字符串吗? 或者任何摆脱语法错误的方法? 谢谢!

【问题讨论】:

  • 您的预期输出不是有效的语法。你的意思是a= '"x" "y" "t" "id" "id2"'
  • 之前的行中看起来像左开括号。
  • @roganjosh 是的,我想要一个像你说的那样
  • @KlausD。不,这不是问题。代码在 Jupyter notebook 中运行良好。我猜这不是有效的 shell 语法,但我不知道如何使用 shell 命令获取相同的字符串
  • 什么版本的 Python?

标签: python string shell syntax-error quotation-marks


【解决方案1】:

现在得到答案:

res= "\"x\" \"y\" \"t\" \"id\" \"id2\""

适用于 Shell 和 Python

【讨论】:

    【解决方案2】:

    f-strings 或 formatted string literals 仅受 python 3.6 支持。如果您使用的是旧版本的python,请尝试升级。如果您同时安装了 python2 和 python3,请确保您正在启动 python3

    但是对于您期望的输出,您不需要 f-strings

    res = '"x" "y" "t" "id" "id2"'
    

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 2019-01-11
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      相关资源
      最近更新 更多