2

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.

1
  • 1
    So you want the output as: output: 123.234 1.548 99.999, right? Commented Feb 1, 2021 at 12:45

2 Answers 2

2

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)))
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.