简体   繁体   中英

format string python with varying number of placeholders

    def SumFunc(E,n):
        write_path = open('somepath.text','a')
        some function here evaluates the following...
        c1 = 
        c2 = 
        c4 = 
        c4 =  
        write_path.write('{} {} {} {} {}\n'.format(E,c1,c2,c3,c4))

I have a function with depends on 'E' and 'n' , where 'n' is the number of place holders in the end, which in this case is 5. My 'n' varies from 4 to 100 for different examples.

My question is how can I format the writing on file so that it works for all 'n' . Like in n=4 it writes with 4 place holders and when n=50 it creates 50 placeholders and write 50 values.

Thanks

Have your values ( Cs ) stored in a list let's call it c_list

Then generate your string this way:

string = ' '.join([str(x) for x in c_list]) + '\n'
write_path.write(string)

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