Python Forum
confused about string formatting - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: confused about string formatting (/thread-36565.html)



confused about string formatting - barryjo - Mar-05-2022

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.


RE: confused about string formatting - deanhystad - Mar-05-2022

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.


RE: confused about string formatting - barryjo - Mar-05-2022

What you say works. Thanks


RE: confused about string formatting - snippsat - Mar-05-2022

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~~~~~~~~



RE: confused about string formatting - barryjo - Mar-05-2022

This is good info.

But, if I had a number like 1.12345

How would I format it to read 01.12 ?


RE: confused about string formatting - deanhystad - Mar-05-2022

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*



RE: confused about string formatting - barryjo - Mar-05-2022

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.


RE: confused about string formatting - snippsat - Mar-06-2022

If lazy 💤
>>> n = 1.12345
>>> print(f'Number is 0{n:0.2f}')
Number is 01.12