-2

我有一个功能。它打印字符串。我怎样才能最好地在列表中收集这些字符串?

IE

def FUN(a):
...
    print(somestrings)
4

2 回答 2

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']
于 2013-10-30T21:14:44.347 回答
0
x = list()

x.append(strings1)  # use a loop of some sort to append your strings
x.append(strings2)
. 
.
.
x.append(stringsN)

return x
于 2013-10-30T20:24:27.670 回答