assign output of print to a variable in python

前端 未结 6 1417
心在旅途
心在旅途 2021-01-15 01:41

i want to know how to assign the output of print to a variable.

so if

mystring = \"a=\\\'12\\\'\"

then

print mys         


        
6条回答
  •  抹茶落季
    2021-01-15 02:20

    Redirect stdout and capture its output in an object?

    import sys
    
    # a simple class with a write method
    class WritableObject:
        def __init__(self):
            self.content = []
        def write(self, string):
            self.content.append(string)
    
    # example with redirection of sys.stdout
    foo = WritableObject()                   # a writable object
    sys.stdout = foo                         # redirection
    
    print "one, two, three, four"            # some writing
    

    And then just take the "output" from foo.content and do what you want with it.

    Please disregard if I have misunderstood your requirement.

提交回复
热议问题