简体   繁体   中英

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))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM