简体   繁体   中英

Apply the same string format to a varying number of variables

Is there a way to apply the same format to a list of multiple real variables without a necessity of making a list? There are a lot of tutorials, but every one of them omits this problem. Say, I have reals:

variable = 123.234
another = 1.54816
var = 99.9994

Comparing to Fortran, I want to get ( '_' representing a whitespace):

write(*,'(3f8.3)') variable, another, var

output:

_123.234___1.548__99.999

or something like this in Python:

print("{:8.3f}".format(variable, another, var))

preserving the same output as for Fortran.

I know I can make a list of variables and then use a for loop, but I'd rather avoid that since it introduces unnecessary lines in the code.

How about:

var1, var2, var3 = 123.234, 1.54816, 99.9994
# print('output: {:7.3f}   {:7.3f}  {:7.3f}'.format(var1, var2, var3))
print('output:' + (' {:7.3f} '*3).format(var1, var2, var3))

You will get:

output: 123.234     1.548   99.999

To preserve the varying nature of the original code (to an extent), you can use the str.join method with a generator expression , and pass as many variables as you need, without needing to change the string itself:

print(''.join(f"{num:8.3f}" for num in (variable, another, var)))

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