Reputation: 730
this is my problem:consider a number like 29.8245,given an amount for precision first this number should be rounded,for instance for precision =0
it would be 30.Now this number should be center aligned in a string with a given width. for instance if width = 10
then the final result would be:' 30 '
For this particular example I came up with:
"{:^10}".format("{0:.0f}".format(29.8245))
the problem is that now the numbers are hard coded and I don't know how to fix that to get the inputs into my code.I know that :
"{}".format()
is what we use in normal cases but in this problem I don't know how to combine these two codes(I don't even know is it possible or not). Also is there a better approach to solve the problem?
Upvotes: 3
Views: 2125
Reputation: 362766
This is exactly why format strings support nesting:
>>> width = 10
>>> precision = 0
>>> num = 29.825
>>> f'{num:^{width}.{precision}f}'
' 30 '
Upvotes: 3
Reputation: 123473
Here's one way to do it the will work in "old" versions of Python (before 3.6) and will continue to work in it as well:
res = "{:^{width}.{precis}f}".format(29.8245, precis=2, width=15)
print(repr(res))
As you can see, format string syntax supports nesting.
Output:
' 29.82 '
The values used for precis
and width
are expressions, so could involve calculations rather than being hardcoded constants as shown.
Upvotes: 1
Reputation: 684
Here is another possible solution that doesn't rely on f-strings
>>> '{0:^{width}.{precision}f}'.format(12.34, width=10, precision=0)
' 12 '
Upvotes: 1