Python 3 打印()到变量 [英] Python 3 print() to a variable
问题描述
在 Python 3 中,您可以使用 print 函数将数据写入文件(例如 print('my data', file=my_open_file)
.这很好(而且非常酷)). 但是你能打印
到一个(字符串?)变量吗?如果可以,怎么做?
In Python 3, you can use the print function to write the data to a file (e.g. print('my data', file=my_open_file)
. This is well and good (and very cool). But can you print
to a (string?) variable? If so, how?
在我的特定用例中,我试图避免将数据写入磁盘上的临时文件,只是为了打开和读取该临时文件.
In my specific use case, I am trying to avoid writing the data to a tempfile on disk just to turn and read that tempfile.
我不能仅仅分配,因为我的源数据不是字符串,而是由 BeautifulSoup 提取的 html 文档树的一部分.提取文档树后,我将逐行处理它.
I'm can't just assign because my source data isn't a string, rather it's part of the html document tree as extracted by BeautifulSoup. Once I have the document tree extracted, I'm going to process it line by line.
我的代码:(现在工作!)
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)
<小时>
更好的工作代码:
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)
推荐答案
基于更新问题的更新响应
如果您需要做的只是将对象转换为字符串,只需在变量上调用 str
函数...这就是 print
在内部所做的.
If all you need to do is convert your object as a string, simply call the str
function on the variable... this is what print
does internally.
a = str(soup.find('body'))
调用 print
可以做很多其他的事情,如果你只需要一个字符串表示的话.
Calling print
does a whole bunch of other stuff that you don't need if all you need is a string representation.
原始回复
您可以使用 io.StringIO.
import io
f = io.StringIO()
print('my data', file=f)
# to get the value back
a = f.getvalue()
print(a)
f.close()
请注意,在 python2 上,这是在 StringIO.StringIO
下.
Note that on python2 this is under StringIO.StringIO
.
这个解决方案适用于当您有想要打印到文件的预先存在的代码,但您更愿意在变量中捕获该输出时.
This solution is good for when you have pre-existing code that wants to print to file, but you would rather capture that output in a variable.
这篇关于Python 3 打印()到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!