+ 1
[ANSWERED] F-string or .format()?
What would be a more efficient way to declare variables?
4 Antworten
+ 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 :)
+ 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
+ 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)
+ 1
Tibor Santa, thanks! That was the answer I was looking for! Much appreciated. ♥️