我有一个功能。它打印字符串。如何在列表中最好地收集这些字符串?
即。
def FUN(a):
...
print(somestrings)
答案 0 :(得分:0)
x = list()
x.append(strings1) # use a loop of some sort to append your strings
x.append(strings2)
.
.
.
x.append(stringsN)
return x
答案 1 :(得分:0)
您可以暂时将sys.stdout
更改为自定义类:
import sys
def fun(a,b):
print(a)
print(b)
class Catcher:
def __init__(self):
self.res = []
self.stdout = sys.stdout
sys.stdout = self
def write(self, chars):
self.res.append(chars)
def call(self, fun, *args, **kwargs):
fun(*args, **kwargs)
sys.stdout = self.stdout
return self.res
print(Catcher().call(fun, "hello", b="world!"))
=> ['hello', '\n', 'world!', '\n']