In fortran, I am able to repeat a format descriptor to save rewriting it many times, for example:
write(*,'(i5,i5,i5,i5,i5)')a,b,c,d,e
could be rewritten as
write(*,'(5(i5))')a,b,c,d,e
Can a similar approach be used in python?
For example, say I wanted to do the same in python, I would have to write:
print "{0:5d} {1:5d} {2:5d} {3:5d} {4:5d}".format(a,b,c,d,e)
Is there some way to repeat the format descriptor, like in fortran?
In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.
"f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string. It is safe to call this function with a value of “None” (because the “None” value in Python is an object and can have methods.)
You can repeat the formatting string itself:
print ('{:5d} '*5).format(*values)
Format string is a normal string, so you can multiply it by int
>>> '{:5d} '*5 '{:5d} {:5d} {:5d} {:5d} {:5d} '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With