Danny
Danny

Reputation: 157

How to store a print output to variable?

I wanted to know if there was a way to reproduce an output from one section of a code to the end of the code. So I am assuming I need to assign a variable to the print output function. Anyway this is part of my code that I want to store variable output to a variable and reproduce an output anywhere in my code:

for busnum,busname,scaled_power in busses_in_year[data_location]:
        scaled_power= float(scaled_power)
        busnum = int(busnum)
        output='Bus #: {}\t Area Station: {}\t New Load Total: {} MW\t'
        print(output.format(busnum,busname,scaled_power))

Upvotes: 1

Views: 4121

Answers (1)

Zach Gates
Zach Gates

Reputation: 4130

You'll need to assign the result of output.format to a variable; not the value of the print function.

formatted_output = output.format(busnum, busname, scaled_power)

The print function will always return None. In your loop, if you need the output for each iteration, store them in a list.

outputs = []

for busnum, busname, scaled_power in busses_in_year[data_location]:
    scaled_power = float(scaled_power)
    busnum = int(busnum)
    output = 'Bus #: {}\t Area Station: {}\t New Load Total: {} MW\t'
    formatted = output.format(busnum, busname, scaled_power)
    outputs.append(formatted)
    print(formatted)

Upvotes: 4

Related Questions