+ 1

[ANSWERED] F-string or .format()?

What would be a more efficient way to declare variables?

21st Jan 2020, 1:58 PM
Mr. Cat
Mr. Cat - avatar
4 Respuestas
+ 4
The f-string is a relatively new feature (python 3.6) so if you have to use earlier versions for any reason, or be backwards compatible, then you can't use them. But generally I prefer f-string for its brevity :)
21st Jan 2020, 3:38 PM
Tibor Santa
Tibor Santa - avatar
+ 7
Here is a link to a (hopefully) tutorial about the different kinds of formatting strings: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-string-formatting/ Here is an other link that covers a lot of aspects about string formatting: https://stackoverflow.com/questions/5082452/string-formatting-vs-format
21st Jan 2020, 3:16 PM
Lothar
Lothar - avatar
+ 3
I think, internally it should be the same: According to your specifications, a new string is created. So it's probably a matter of taste which of these you choose: x = 1.23456 a = f'x: {x:.2f}' b = 'x: {:.2f}'.format(x) c = 'x: '+format(x, '.2f') d = 'x: %.2f'%x print(a, b, c, d)
21st Jan 2020, 2:38 PM
HonFu
HonFu - avatar
+ 1
Tibor Santa, thanks! That was the answer I was looking for! Much appreciated. ♥️
21st Jan 2020, 3:39 PM
Mr. Cat
Mr. Cat - avatar