Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string formatting on the fly

I have a situation where I don't necessarily know how I'd like to format some string until I've calculated the length of some other number.

Doing something like:

"{0:.2f}".format(#)

works well because I know that I'd like to display that many places, two in this case, past the decimal point. What if the number of places is subject to change? How would I do dynamic string formatting of the elements of a list called B (that is I'd like to place appropriately formatted elements of B into a string), from the corresponding elements of a list called A?

A = ['1.100','5.4','11.1','7']
B = [1.23474927,4.92837087,12.06532387,6.9998123]

The answer that I would ideally like to see is the following:

C = ['1.235','4.9','12.1','7']

Here's what I know so far:

1) I can figure out how many places to the right of each string within A by doing:

places_A = [len(A[i].partition('.')[2]) for i in range(len(A)]

The real question is: How do I then dynamically tell format() to keep that many places to the right of the decimal point?

like image 947
astromax Avatar asked Dec 14 '22 22:12

astromax


2 Answers

You just need more cowbells (actually, more replacements: {}):

print "This is a number with {1} places {0:.{1}f}".format(3.14159, 2)

Or, in the example you gave:

C = ['{0:.{1}f}'.format(b, len(a.partition('.')[2])) for a,b in zip(A,B)]
like image 74
Robᵩ Avatar answered Dec 17 '22 11:12

Robᵩ


With classical string formatting:

>>> d = 2
>>> f = "%%.%sf" % d
>>> f
'%.2f'
>>> f % 5.0
'5.00'

That is, first dynamically create your format string, and then use that format string for converting your float to a string. That concept is translatable to the modern string formatting syntax.

like image 26
Dr. Jan-Philip Gehrcke Avatar answered Dec 17 '22 13:12

Dr. Jan-Philip Gehrcke