Python String Formatting: f-strings vs .format() vs %

https://slicker.me/python/string-formatting.html

42 points · 15 comments · view on lemmy.world

15 Comments

charokol@lemmy.world · 14 pts · 104d (2 replies)

Didn’t think I’d learn anything new in this article, but I never knew about f-string’s self-documenting expression syntax. I’ve been doing it myself like a chump!

monica_b1998@lemmy.world · 4 pts · 104d (1 reply)

lol, don't be too hard on yourself!

charokol@lemmy.world · 7 pts · 104d

I’m not! I’m excited to forget this exists the next time it would be convenient for me to remember it 😋

olafurp@lemmy.world · 9 pts · 104d (2 replies)

I worked in python when f-strings were pretty new. Didn't realise why you would use anything else. It just reads better.

Michal@programming.dev · 4 pts · 104d (1 reply)

Most importantly you can't use them with translated strings, so it's not usable for user facing strings unless you don't care. This limits fstring usefulness a lot in the projects I work on.

Badabinski@kbin.earth · 9 pts · 104d

Luckily, there's now t-strings (e.g. t"{buh}") for that use case (among many others). Here's the PEP: https://peps.python.org/pep-0750/

NotSteve_@lemmy.ca · 3 pts · 104d (3 replies)

F-strings and .format() are two features I miss from Python whenever I'm writing stuff in another language. The syntax is just so minimal yet powerful

Vulwsztyn@programming.dev · 1 pts · 102d (2 replies)

in what language?

NotSteve_@lemmy.ca · 2 pts · 102d (1 reply)

Go mainly. fmt has some functions to do the same sort of formatting but I loved the minimal syntax in Python. JavaScript has a really nice syntax for it as well actually

Vulwsztyn@programming.dev · 1 pts · 102d

reasonable answer

itsathursday@lemmy.world · 3 pts · 104d (2 replies)

What annoyed me moving from % to format was the loss of “formatting” floats to integers with “{:d}”, now you get a ValueError

ZoteTheMighty@lemmy.zip · 5 pts · 104d (1 reply)

{:.0f} always works though for floats or ints

itsathursday@lemmy.world · 2 pts · 103d

Ah nice one

slag@lemmy.dbzer0.com · 3 pts · 104d

And here I thought f-strings were something that happen when others are forced to read my code.

Stefan_S_from_H@piefed.zip · 0 pts · 104d

Formatting strings, the running gag of the Python community.