我有一个功能。它打印字符串。我怎样才能最好地在列表中收集这些字符串?
IE
def FUN(a):
...
print(somestrings)
您可以暂时更改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']
x = list()
x.append(strings1) # use a loop of some sort to append your strings
x.append(strings2)
.
.
.
x.append(stringsN)
return x