r/learnpython • • 16d ago

Are f-strings enough?

I've been learning python mainly from bro code's videos and he uses f strings for basically everything. It comes to me naturally to use them and I understand them. I found a book (Kenneth A. Lambert: Fundamentals of python: first programs, second edition) and here he uses other type of strings (I assume this would be the basic way) but I honestly don't understand them especially when it's about formatting (.2f etc). Should I learn this basic way of working with strings now? Or are f strings enough?

I should add that I'm learning python for fun, I'm studying mechanical engineering, so I know it can be very useful. I also want to be good at it in a potential work environment (?)

28 Upvotes

44 comments sorted by

View all comments

Show parent comment

1

u/markhahn 14d ago

how often is repr/str expensive? if it's just a string, the cost is negligable (probably smaller than a function call).

rather than messing up the preferred formatting mechanism, I'd look at the traditional approach (let logging.debug expand, macro-like, into a condition in the calling context). viewed in this light, isn't this largely a quality-of-compilation issue?

2

u/Discordbothost 14d ago

honestly rarely. most of the time it's noise and f-strings are fine. the cases i've actually hit were dataframes, big dicts of api responses, and orm objects whose repr touched lazy-loaded fields (that one hit the db, fun to find)

and yeah, python has no macros so the closest you get to the "expand into a condition" approach is doing it by hand:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug(f"state: {expensive()}")

which i'd only bother with on hot paths. so i'd agree it's mostly a language/compilation limitation, not a reason to avoid f-strings everywhere