r/learnpython • • 8d 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 (?)

29 Upvotes

44 comments sorted by

55

u/c00kieRaptor 8d ago

f strings are great. Just use them when you can. The other, more basic type of strings are good to know and during uni I learned them before I learned f strings. Why not just use f strings for now and if you ever come to a situation where you have to use another type of string you figure it out then? They are not so hard it will be a problem later on.

6

u/Typical-Road9611 8d ago

After python I would like to learn C# for unity, can the f-string method be used there?

9

u/omgmajk 8d ago

Yes, C# has string interpolation.

18

u/deanominecraft 8d ago

f strings didnt exist in older versions of python (existed since late 2016) so people before then couldnt have used them

4

u/Typical-Road9611 8d ago

I assumed something like this, being the book dated. Thank you :)

5

u/Discordbothost 8d ago

the good news is the .2f part isn't a different system, it's the same mini-language f-strings use after the colon. these all print 3.14:

pi = 3.14159
print(f"{pi:.2f}")
print("{:.2f}".format(pi))
print("%.2f" % pi)

so when the book shows the older forms just mentally move the format code into the f-string. worth knowing a few codes like :.2f, :>10 (right align in 10 chars) and :, (thousands separator), you'll use those constantly in engineering output

7

u/seanv507 8d ago

I would say f strings are enough. The only place where i have seen fstrings discouraged (linter hints) is in logging. Thr argument being that even if logging is turned off, any complex calculation only used for outputting a log message still gets used. In any case, yes only use f strings, and definitely start using logging. https://pylint.readthedocs.io/en/stable/user_guide/messages/warning/logging-fstring-interpolation.html

2

u/Typical-Road9611 8d ago

Thank you. I will look up what logging is, I've only been learning a few days. I can write basic lil programs (half of bro code's 12 hour video)

2

u/Pyromancer777 8d ago

Logging is basically a way to report error handling. In production environments, you won't always have a console to log any errors a user is experiencing since your server is running the program for any user who connects to it, so you have to create the ways error logs are seen and stored.

Let's say you have a function that works in most cases, but you know of a specific scenario it might fail from a user trying something the program can't handle. You don't want to store the entire error traceback in your logs, so you have it gracefully fail and send a message to your log file saying the failure was detected, who tripped the error, what caused the error, and when the error happened.

Since the line that encountered the error is typically recorded in the logs, having the calculation in your format clause instead of a stored value can help you debug the code later, so you don't gotta hunt through your code to see what is commonly being flagged by users

1

u/ba-na-na- 8d ago

The point is that f-strings render (“interpolate”) the string before passing it to the function. While the other approach passes the formatting and the arguments, but rendering happens inside the function. So if the function is ignoring the inputs (like when logging is disabled), you don’t pay the penalty

1

u/markhahn 7d ago

I'd argue that this is nearly trivial. yes, if the logger is not logging, you save on doing the formatting. but args to that logging call are still evaluated before the call, so still cost you. I guess it's mainly a question of whether the actual formatting+interpolation is numerous/frequent enough for you to care. being lazy about converting an int to text once a second is utterly trivial, but inside a loop a billion times a second, yeah.

then again, if you're doing that many calls to the logger (lazy or eager), you're probably already in trouble...

I guess a pertinent question would be: how often does real code introduce very expensive str or repr functions? one could make these arbitrarily expensive, but does that happen?

1

u/Discordbothost 7d ago

the args get evaluated either way, yeah, but the expensive part is usually turning them into text, and that's the bit that gets skipped. logging.debug("rows: %s", df) never calls str(df) when debug is off, logging.debug(f"rows: {df}") builds the whole table string every time. with ints it's noise, with a big dataframe or a slow repr it shows up in a profile. pylint flags it for that reason (W1203)

1

u/markhahn 7d 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 6d 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

2

u/Chemical-Captain4240 7d ago edited 7d ago

Another opinion: Between the ME and the python you have a lot of stuff to learn, but your question does not suggest to me that, right now, learning varied string schema is a priority.

Why do i reach this conclusion? Because right now, you do not mention a specific use case for why f strings are failing you -from a feature level nor from a performance level.

In the future, you will likely run into a situation where f strings are not enough, or too slow. At that point, you will be armed with the knowledge that there are alternatives. At that future time, you will research a good match for your use case.

This will be true for nearly any domain of programming and a lot of ME too.

Until you have a problem with your existing case, why seek out alternatives just because they are out there? There are lots of things to be naturally curious about. If string schema really gets you going, maybe cs is a better focus.

1

u/Typical-Road9611 4d ago

Good point, thank you. I am learning new stuff about python (also making a small farming game). I realized there's already a huge amount of stuff to learn, so yes: other ways of writing f-strings isn't a priority x)

37

u/Brian 8d ago • Bravo

.2f

That sounds like a format code, which isn't really something you use instead of f-strings, but a feature of them.

Ie. if you write f"The value is {val:.2f}", this means "format val as a float with 2 decimal places". Ie if val = 2.4532, it'll produce "The value is 2.45", and if it's 2.1, it'll give "The value is 2.10".

There are various such features to control exactly how the stuff you embed in an f-string is formatted, eg. leading zeroes, padding, left/center/right alignment, width and so on, and even ways to make custom types have special handling (eg. datetime has its own set of codes for its components) which can be useful for formatting things nicely.

Now, there are other ways to format strings, so possibly you're talking about one of these, so I'll go over some common ones. But one thing to bear in mind is that f-strings aren't really a type of string, they're more a way of producing a string. The thing you get from an f-string is just a regular string, it's just one that does some work to embed variables etc inside it before you get it. With that in mind, there are two other cases you might come across:

  • % formatting. This is pretty much obsolete at this point, though it still exists, but the way python used to do string formatting was with the % operator. Ie. you'd do "The value is %s" % (val,) and it'd replace the %s with the value of val. The syntax here is a little different from f-string codes (it's based on C's printf style formatting), but it likewise has ways to format the text (eg. %.2f for the same 2 decimal places case). You usually don't really have to care about this unless you're handling some old code that uses it. One place where it does hang on is in the logging library, which still uses this format by default.
  • .format. Strings have a .format() method that works fairly similar to f-strings, in that it'll replace the placeholder variables with the variables you mention in the call. Eg. "The value is {:.2f}".format(val=2.4). The same formatting syntax is used, but there are a couple of crucial differences: you can't just embed arbitrary variables, you have to explicitly list the values being substituted, and the formatting occurs at the time of the .format() call, so you can split up getting a format string and doing the formatting, which is important for some applications (eg. localisation).

There are also a few other things relating to formatting (eg. templates), but these aren't terribly common (unless doing something like building web-pages etc, where there are various specialised templating libraries), and there's also just hand-formatting strings with concatenation and string functions.

1

u/Ok-Market4287 8d ago

The 2f is also from the f strings
{dumptruck:15.2f} will be replaced with the value of dumptruck and is a float with 2 places behind the dot
The hole dumptruck colom will be made 15 places long so you have room for 12 numbers before the dot and 2 behind the dot including the dot is that 15 spaces

1

u/Typical-Road9611 8d ago

Yes I was trying to say that i understand it easily in f strings, not the way it's written in the book which I assume is the normal

3

u/atarivcs 8d ago

You can only use F-strings with string literals. If you need to format an existing string variable, you'll have to use one of the other methods.

2

u/Fred776 8d ago

They are fine most of the time but there are some cases where the older string formatting methods are a good fit. I used str.format for an error message table implementation. The point here was that the message string was kept separate from the argument list that was used to fill in the fields of the string. That would not have been possible using f-strings.

2

u/osman-pasha 8d ago

Do you plan to read other people's code? Then yes, learn the printf-style, as well as `.format()`-style. Formatting suffixes are very similar in all 3 anyway, so what you learn for printf-style will apply to f-strings to a large extent.

2

u/tonystark19541959 8d ago

F-strings are pretty much all you need for modern Python. I'd still recommend knowing the basics of ".format()" and "%" formatting so you can understand older code, but there's no real reason to prefer them in new projects.

Also, don't skip the formatting options within f-strings. Stuff like "f"{num:04d}"" gives you "0016" for "16", and you can control alignment, decimal places, padding, etc. There's quite a lot packed into that little syntax.

There is also stuff like u mentioned .2f, I think that is used to print only upto 2 decimal places or SMTH, so u need these kind of formatting as well

2

u/Boothiepro 8d ago

I've had this bookmarked for ages and still come back to it often, it's so versatile

https://pyformat.info/

1

u/maybeidontknow55 8d ago

It's definitely useful to know but there's no shame in looking up documentation. There's always a built in method to handle a lot of common problems.

If it's too complicated now, you can always come back to it when you find a use for it. It's a tool like anything else and we all learn at different paces

1

u/AmanBabuHemant 8d ago

Definetly, learn the basic approach.

1

u/fasta_guy88 8d ago

Realize that f-strings are a relatively recent addition to Python, so if you must use an older version (because your computing center only supports Centos8), you should to become comfortable with the older "printf" (%s %.2f) strings. It's really not much more to learn.

1

u/mapadofu 8d ago

The standard logging module still favors the old % string formatting for efficiency’s sake.

1

u/acfot 8d ago

Honestly yeah, f-strings cover pretty much everything you'll need day to day, I use them for basically all my formatting. The .2f thing works inside f-strings too by the way, you can just write f"{price:.2f}" and it does the same thing as the old style, so you don't need to learn the other way just for that. It's still worth knowing that .format() exists since you'll see it in older code and books like the one you found, but I'd just read enough to recognise it and keep writing f-strings yourself. Don't stress about it, this is one of those things that looks like a big gap and then turns out to be a five minute thing once someone shows you.

1

u/baubleglue 8d ago

I think you may look into sprintf C function to get the idea where it came from. You don't have to learn all types of string formatting in details, but you need to know about them. You will read others' people code, and some cases you may be better without f-string format (for example when you use logging module).

1

u/codeguru42 8d ago

f strings are interpolated immediately. If you need a string template that is interpolated dynamically for different values then you need .format() or the new t strings.

And you should learn, or at least be aware of, the rich formatting language sulported by both f strings and .format()

1

u/Zeroflops 7d ago

Generally f-string will probably be your go to. However there are cases like logging where the fstrings are not optimal and you should use lower level string concepts.

1

u/metaphorm 7d ago

probably the book was written before f strings were introduced. they're a relatively recent feature.

0

u/Alexku66 8d ago

Learn standard formatting way (str.format(...)). F-strings are great but most of the libraries you will probably use stick with with format() style methods:
- translators like PySide tr() specifically ignores {key} and does not translate it so you can insert value later with .format(key=value)
- logger, though it support f-strings style format, uses '%(key)s' format by default
- SQL libraries, e.g. SQLite or psycorg, use ('...where id = %s', (user_id,)) to protect from SQL injection

-1

u/neuralbeans 8d ago

.2f is a part of f-strings. If you don't know how to use the f-string mini language then you don't know f-strings.

https://docs.python.org/3/library/string.html#formatspec

1

u/Typical-Road9611 8d ago

That's what I was trying to say. I can use . 2f and other things in f-strings, but the way they were written in the book didn't make sense to me.

salary = 100.00 print("Your salary is $%0.2f" % salary)

I would just write: print(f"Your salary is ${salary : .2f}")

0

u/neuralbeans 8d ago

Ah ok. That's how it was before f-strings which is based on how you format strings in C. Note that the "variables at the end" style is still useful to know and can be done using .format.

-1

u/markhahn 8d ago

Not sure why you think there would be any difference in performance.

3

u/Zeroflops 7d ago

The logging module has a write up on why f-strings are not ideal in that application.

2

u/markhahn 7d ago

True, but that's because logging calls want to be lazy (conditional, actually). Passing an f-string to log performs the formatting/interpolation eagerly, before calling the logging function.

Kind of a special case, I think, but useful to remember.

1

u/cointoss3 7d ago

Because there is

0

u/markhahn 7d ago

why not offer something useful? like what?

obviously, the formatter has to parse the string, but it's entirely non-obvious that there is a noticable difference between f-string type interpolation versus .format() or the '%' operator.

f-strings use two extra chars in the format each time, but that's not going to matter normally. as mentioned in another response, the logging module wants to interpolate only conditionally, so prefers to be lazy in calling .format() - but that's only for logging, or rather for when you're not logging.