Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I repeat a string format descriptor in python?

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?

like image 870
tmdavison Avatar asked Jun 24 '13 14:06

tmdavison


People also ask

How do you repeat a string in Python?

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.

What does {: 3f mean in Python?

"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.

What is str format () in Python?

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.

What does __ format __ do in Python?

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


1 Answers

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} ' 
like image 94
Jakub M. Avatar answered Sep 18 '22 22:09

Jakub M.