将表达式赋给变量并执行它

时间:2017-11-27 17:18:41

标签: python

我想将以下表达式分配给变量:

textFormat = 'soup.find("div", {"class" : "article-entry text"}).text.replace(\'\n\', "")'

我使用

在另一个文件中调用此代码
text = exec(textFormat)

可悲的是我收到错误消息:

   File "C:\Users\dadsad\documents\coding\dasdasd\functions.py", line 42, in loadAtom
    text = exec(textFormat)   File "<string>", line 1
    soup.find("div", {"class" : "article-entry text"}).text.replace('
                                                                    ^ SyntaxError: EOL while scanning string literal

有什么想法吗?谢谢! :)

编辑:试过这个建议,得到一个无: enter image description here

1 个答案:

答案 0 :(得分:5)

我怀疑你患有反疱疹。在n

之前还需要一个斜杠
textFormat = 'soup.find("div", {"class" : "article-entry text"}).text.replace(\'\\n\', "")'

但是,这样代替exec代码,你可能想要公开一个子程序:

def textFormat(soup):
    return soup.find("div", {"class" : "article-entry text"}).text.replace('\n', "")