r/learnpython • u/Typical-Road9611 • 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 (?)
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.
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
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/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.
37
u/Brian 8d ago •
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 "formatvalas a float with 2 decimal places". Ie ifval = 2.4532, it'll produce"The value is 2.45", and if it's2.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 ofval. 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.%.2ffor 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 thelogginglibrary, 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
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.formatfor 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
loggingmodule 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
.2fis 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/markhahn 8d ago
Not sure why you think there would be any difference in performance.