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