Python 3 打印()到变量

Min*_*Web 2 python printing python-3.x

在 Python 3 中,您可以使用 print 函数将数据写入文件(例如print('my data', file=my_open_file)。这很好(而且非常酷)。但是您可以print写入(字符串?)变量吗?如果可以,怎么做?

在我的特定用例中,我试图避免将数据写入磁盘上的临时文件,只是为了打开和读取该临时文件。

编辑:我不能仅仅分配,因为我的源数据不是字符串,而是由 BeautifulSoup 提取的 html 文档树的一部分。提取文档树后,我将逐行处理它。


我的代码:(现在工作!)

with open("index.html", "r") as soup_file:
    soup = BeautifulSoup(soup_file)
THE_BODY = soup.find('body')
not_file = io.StringIO()
print(THE_BODY, file = not_file)    # dump the contents of the <body> tag into a file-like stream
with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
    for line in not_file2.getvalue().split('\n'):
        print("headerblock += '{}'".format(line), file = HEADER_JS)
Run Code Online (Sandbox Code Playgroud)

更好的工作代码

with open("index.html", "r") as soup_file:
    soup = BeautifulSoup(soup_file)
with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
    for line in str(soup.find('body')).split('\n'):
        print("headerblock += '{}'".format(line), file = HEADER_JS)
Run Code Online (Sandbox Code Playgroud)

Set*_*ton 6

基于更新问题的更新回复

如果您需要做的只是将对象转换为字符串,只需str在变量上调用函数……这就是print内部所做的。

a = str(soup.find('body'))
Run Code Online (Sandbox Code Playgroud)

print如果您只需要字符串表示,则调用会执行您不需要的一大堆其他东西。


原始回复

您可以使用io.StringIO

import io 
f = io.StringIO()
print('my data', file=f)

# to get the value back
a = f.getvalue()
print(a)
f.close()
Run Code Online (Sandbox Code Playgroud)

请注意,在 python2 上,这是在StringIO.StringIO.

当您有想要打印到文件的预先存在的代码,但您更愿意在变量中捕获该输出时,此解决方案很有用。