【问题标题】:Python EOL error in Exec function which evaluates to include a string containing a quoteExec 函数中的 Python EOL 错误,其计算结果为包含包含引号的字符串
【发布时间】:2021-08-17 22:31:25
【问题描述】:

我正在编写一个要执行的字符串,以将值分配给 json 文件中的任意深度点,我分配的值是字符串,其中一些字符串包含引号,这是我得到错误的地方。

我尝试用“替换我分配的字符串中的“,将我分配的字符串用三引号括起来。

此外,以下所有内容均未以三引号开头,这只是解决此问题的最新尝试。

代码

for index, row in md_csv.iterrows():
    json_ref_string = ''
    for k in row['Path']:
        json_ref_string += "['"
        json_ref_string += k
        json_ref_string +="']"
    my_string ="""jo"""+json_ref_string+"""="""+"""\""""+str(translated_csv.iloc[index][1])+"""\""""
    exec(my_string)

错误

    File "/Users/maxgreen/opt/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3437, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-244-a1adf20fc0ec>", line 9, in <module>
    exec(my_string)

  File "<string>", line 1
    jo['agreementinfo']="Estoy celebrando este acuerdo en nombre de la parte contratante cuyos detalles he presentado en la página "INFORMACIÓN COMERCIAL", en adelante, el "COMERCIANTE""
                                                                                                                                    ^
SyntaxError: invalid syntax

【问题讨论】:

  • python_object = eval(my_string)?
  • 尝试添加 print(my_string) 以查看您要执行的操作。
  • 如果你使用原始 f 字符串可能会更容易。

标签: python string escaping exec


【解决方案1】:

来自 cmets 中 barmar 的建议使用字符串文字工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多