简体   繁体   English

如何打印到 Python 中的字符串

[英]How to print to a string in Python

Lisp type languages usually provide an abstraction which allows you to open a string as a file, and then print to it using any function which can normally print to a file. Lisp 类型语言通常提供一个抽象,允许您将字符串作为文件打开,然后使用通常可以打印到文件的任何 function 打印到它。 When you close the string you can recuperate the string that was printed.当您关闭字符串时,您可以恢复打印的字符串。

Does something like this exist for python? python 是否存在类似的东西?

It probably would like something like this:它可能喜欢这样的东西:

f = open_string_as_output()
f.write("hello")
if some_condition:
   f.write(" ")
g(f) # allow g to write to the sting if desired
f.close()
str = f.get_string()

There is a class called StringIO , which does what you described.有一个名为 StringIO 的StringIO ,它可以执行您所描述的操作。

import io
string_out = io.StringIO()
string_out.write('Foo')
if some_condition:
    string_out.write('Bar')
string_out.getvalue()  # Could be 'Foo' or 'FooBar'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM