I am confused about string formatting.
If I have a number 14.20003 I want to make it into a string s = 14.20
Do I use the "f" format or the "%" format?
what is the best way for the above example.
a = f"{14.2000003:0.2f}"
b = "{:0.2f}".format(14.2000003)
c = "%0.2f" % 14.2000003
print(a, b, c)
Which do you like best? They all work fine.
Output:
14.20 14.20 14.20
I would go with the top since this is the most recent way to format. It must improve over shortcomings in the previous methods. I like how you embed the value in the same string as the formatting controls. b uses pre-3.6 Python formatting. I don't like how the values are at the end. It is easy to make a mistake on format strings with lots of values. The % formatting is ancient.
What you say works. Thanks
f-string is definitely what you should use now,it's more readable and also faster.
If make some more variables it easy to see this they are where the belong in string and not last.
>>> store = 'Walmart'
>>> fruit = 'apple'
>>> cost = 14.20003
>>> print(f'A {fruit} at {store} cost {number:0.2f}')
A apple at Walmart cost 14.20
Vs
.format()
that was new in Python 2.6
>>> print('A {} at {} cost {:0.2f}'.format(fruit, store, cost))
A apple at Walmart cost 14.20
A couple more.
# f-strings can take any Python expressions inside the curly braces.
>>> cost = 99.75999
>>> finance = 50000
>>> print(f'Toltal cost {cost + finance:.2f}')
Toltal cost 50099.76
>>> name = 'f-string'
>>> print(f"String formatting is called {name.upper():*^20}")
String formatting is called ******F-STRING******
>>> for word in 'f-strings are cool'.split():
... print(f'{word.upper():~^20}')
...
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~~~COOL~~~~~~~~
This is good info.
But, if I had a number like 1.12345
How would I format it to read 01.12 ?
print(f"{1.2345:05.2f}")
print(f"{1.2345:*>5.2f}")
print(f"{1.2345:*<5.2f}")
Output:
01.23
*1.23
1.23*
So the 05 means a total of 5 spaces (including the decimal) and the.2 means 2 places to the right of the decimal.
Got it.
If lazy 💤
>>> n = 1.12345
>>> print(f'Number is 0{n:0.2f}')
Number is 01.12