Skip to main content
 首页 » 编程设计

python之将表达式分配给变量并执行它

2025年05月04日20tuyile006

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

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 

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

编辑:尝试了这个建议,得到一个无:

请您参考如下方法:

我怀疑您患有背斜线炎。 n 前需要多一个斜杠:

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

但是,您可能不想以这种方式执行代码,而是公开一个子例程:

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