you can also change bases in F strings: >>> f'{4:0b}' '100' >>>
@mrab4222Ай бұрын
15:05 Left alignment is the default for strings, but right alignment is the default for numbers.
@johnbennett1465Ай бұрын
When specifying the number of decimal places, it doesn't just truncate, it also zero pads if needed. I.e. f'{1.2:.3f}' results in 1.200 as the result. This can be very useful in getting a column of numbers to align.
@TheFerdi265Ай бұрын
15:34 was completely new to me! I've been coding Python for years, and this is so helpful!
@SaschaMarkusАй бұрын
Formatting datetime with a variable format like you did with the alignment also is very handy and works combined with the debug specifier too >>> df="%H:%M" >>> print(f"{now:{df}}") 19:30 >>> print(f"{now=:{df}}") now=19:30
@lordstevenson9619Ай бұрын
Another nice formatted for numbers num = 123.4566 print(f‘{num}:.5g’) is 123.46 nice way to print a certain significant figures
@glg216Ай бұрын
Thanks!
@IndentlyАй бұрын
Thank you! :)
@marceauhАй бұрын
13:00 I happen to nest f-strings quite a lot as I spend a lot of time converting files to some obscure format with optional fields This allows me to do things like with io.StringIO() as sio: sio.write("something {f'hi {x}! 'if x is not none else ''}") Thats a small example but i really think that nested f-strings help readability in those cases
@IndentlyАй бұрын
Thanks for sharing, I read a few examples in the comments and it looks useful!
@SantiagoRojoАй бұрын
Also useful to generate HTML
@TsankharXXIАй бұрын
Dynamic spacing saved my life, thank you very much. At 15:30 for anyone wondering.
@sovereignlivingsoulАй бұрын
excellent, now i need to do some edits to one of my programs
@elfoyoutube6039Ай бұрын
12:46 I've already needed to nest f-strings together. I don't really remind when I did it, but I have a good example from the video itself: Let's say you want to format the thousands separator to be a point instead of commas or underscore. You could do f'{f'{your_number_here:_}'.replace('_', '.')}'.
@nuynobiАй бұрын
You don't need a nested f-string to do that. This works just fine: `f"{big_num:_}".replace("_", ".")`
@elfoyoutube6039Ай бұрын
@nuynobi True, but the idea is that you could have other stuff in the outer f-string as well instead of resorting to + or ''.join().
@mightyhelper833624 күн бұрын
Nested F-strings are useful if you want to nest an if or generator expression in an f-string. In theory I think you could probably find some use of the walrus operator in there too but none come to mind
@ROldford29 күн бұрын
Raw strings are used extensively for regex patterns, so French strings (love that by the way!) are great if you need variable regex patterns
@storvattsuisseАй бұрын
This is so useful !
@elizabethkirby1782Ай бұрын
Very cool, thanks for all the info
@rsvdark_main28 күн бұрын
12:44 print(f"The project {"was a success" if success else f"didn't run properly because {"there was an error: {exception}" if exception else "something unexpected happened"}"}")
@DaguobDagunanLex25 күн бұрын
Awesome example!🤩
@TransitPacketАй бұрын
Great tricks! The last one is superb.
@user-us8th9zn1gАй бұрын
16:01 you know pycharm has an block edit mode? Click middle mouse button and drag over all 20, then paste
@SantiagoRojoАй бұрын
The fr string is pretty useful to write regular expressions
@DubbiduАй бұрын
I recently used f-strings to format a number to a certain length and start with zeros. It was really useful to create IDs for elements of a table My code went like this row = 4 length = 3 formatted_row = f'row{row:0{length}}'
@GoodWill-s8jАй бұрын
Every F-String in python is censored.
@itsMeAsh0304Ай бұрын
Great video 🎉🎉
@2dapoint424Ай бұрын
Can the custom format inherit from the standard formatter so I can extend to my use case? Currently your custom formatter won't handle :>10s, etc...
@DrDeuteronАй бұрын
time stamp? If you're talking dunder format, you can _always_ call super.
@dragweb7725Ай бұрын
make your custom class inherit from built-in class you want to get format specifier from, then in your __format__ method just put first: try: super().__format__(format_spec) except ValueError: pass match format_spec: (your custom formats) This kind of logic can also be applied on any method you want to inherit behavior from and extend instead of overriding it
@2dapoint424Ай бұрын
@ which standard method do I inherit from? I know hour inheritance works but I don’t know which class to inherit from so I have all the goodness of format plus I extend it to my use case.
@Aodhan2717Ай бұрын
One method that I’ve used in a personal project was to take a character such as ‘|’ as a separator, and have standard formatting on one side and custom formatting on the other. That way you can run through the standard formatting before or after the custom, or handle the two separately if they apply to different parts of your class.
@dragweb7725Ай бұрын
@@2dapoint424 it depends which kinds of existing formats you're after. If you need the ".2f" and and other rounding features, it comes from the float class, if you're searching for alignement features like "_>20" better inherit from the str class, and that's only examples. More generally, if you need format features that are linked to certain kinds of objects, verify the original class's "__format__" method (if possible) and inherit from this class
@DrDeuteronАй бұрын
this is awesome, I finally got bumped up to 3.12 (security restrictions)..TODAY, and I am behind on f-strings. I'm concerned they're not pythonic tho, we'll see. I still haven't learned format strings, which I first saw in 1987.
@vikaspoddar001Ай бұрын
They are pythonic
@RandomWolfPrintingАй бұрын
My schools uses python 3.2.3. It can always be worse. I have resorted to use GitHub codespaces to use an up to date python.
@hedwig7sАй бұрын
How can something built into python not be pythonic
@p1geon4525 күн бұрын
It's just strings on steroids. I was first worried about huge overhead, but they're fast. There's no reason not to use them
@dipeshsamrawat7957Ай бұрын
Thank you 😊
@uplink-on-ytАй бұрын
I got so focused on the format mini-language spec, that I missed the forest for the trees. I completely missed the "format" protocol (custom format specifiers in your video), the conversion specification (the one with the exclamation point, not in your video), the nested f-strings, the nested replacement fields in the format specifier (the :{n}), and I'm yet to find the docs for the date format specifier and other types that may be already defined to have their own format specs.
@schwingedeshaehersАй бұрын
i can see nested f string together with inline array construction/conversion like f" something something {[f"{i.name}:{i.place}" for i in places]} something something "
@richardferretti8208Ай бұрын
More reasons to love python!!
@nuynobiАй бұрын
FYI most of these tips are not specific to f-strings and will work with normal string formatting, ie str.format().
@oida10000Ай бұрын
That is because f string is a short cut for this function (specially since the revision in 3.12) right?
@nuynobiАй бұрын
@oida10000 Could be. I never really thought about how f-strings work under the hood.
@TRADINGPULSE397Ай бұрын
Sir I'm big fan Plz 1 tutorial pymongo plzz Specially only one document insert multiple time data plzz tell me Mere khne ka matlab hai pymongo m collection m ek hi document ko use krke new data br br usi m kaise store kare
@zaairvasquez377Ай бұрын
Thank you.
@hotlamon3965Ай бұрын
Are all these tricks possible when using multi-lined f-strings?
@IndentlyАй бұрын
There might be some complications which I’m unaware of, but for the most part yes.
@Dzjur.Ай бұрын
why all the type hinting? Is this now required for legibility? Since f=1234.5678 clearly makes it a float. This seems to be a reverse from c++ where they now allow auto as a declaration.
@Ismail_Hassan-77Ай бұрын
❤❤ Please, I would like to know the name of the theme you use in PyCharm😊. Thank you
@Briggoes27 күн бұрын
What ide is this?
@spaniard1315 күн бұрын
He mentioned PyCharm
@pointtheblameАй бұрын
Can someone explain why is name and age defined that way with : instead of using "="?
@indyplaygames3066Ай бұрын
the : is used for type addnotation, itindicates the data type of the variable, basically something like name: str = "indy" means that the variablle name is of type string
@pointtheblameАй бұрын
@@indyplaygames3066 so why not just type name = 'indy'? It is obviously a string and the variable is defined ? Is it the same?
@fernandezguilleАй бұрын
It is not necessary to do it, but it helps the editor understand context of the script, and later on you will see an error if you assing another type to that variable. Specially useful for iterables
@pointtheblameАй бұрын
@@fernandezguille Thank you!
@ivanheffner2587Ай бұрын
… when you first hear “dunder” and think it’s a name; then realize it’s “d(ouble)-under(score)”….
@fernandezguilleАй бұрын
Thanks for clarifying this for me!
@falsemcnuggethopeАй бұрын
I'm conflicted about custom format specifiers. The examples used here don't seem useful, as I'd much rather just use the function itself rather than a custom formatter. And if the formatter does something more complicated, why would you bake that functionality inside the formatter? Idk, maybe it can be useful in some rare occasion.
@spaniard1315 күн бұрын
It's super useful! Think about how you would inspect complex Python objects. Sometimes you want a one liner description, sometimes you want specific fields, sometimes you want a complete data dump on screen. The developer who created the object can give you a rich set of options for display.
@murk1eАй бұрын
The first example is broken as the name was used as a literal string
@Lolwutdesu9000Ай бұрын
Isn't this a repost?
@IndentlyАй бұрын
No, I stated that this was a complete video in the intro.
@DrDeuteronАй бұрын
4:45 pro-tip: *never* _ever_ drop the leading zero on a decimal number that is less than one, and not just in coding. I mean in life.
@bronkolieАй бұрын
Unfortunately floating-point numbers don't really have a way of remembering the amount of decimals like that. You'd need a separate variable
@DrDeuteronАй бұрын
@@bronkolie it's a text file. He wrote p = .5678 which should be: p = 0.5678
@bronkolieАй бұрын
@@DrDeuteron sorry, I thought you meant the last zero like in 0.80 vs 0.8
@techkid436 күн бұрын
What is the risk from doing this? I've seen it regularly but this is the first I've heard of it being bad
@ecaltroyerАй бұрын
Me first
@omkar_sawantАй бұрын
You could've just called it F-String Theory
@IndentlyАй бұрын
Thank you for the suggestion
@KeithKazamaFlickАй бұрын
quick maths lol
@squarerootof2Ай бұрын
Why are they called fvck strings?
@WilnerSumagingsingАй бұрын
age = 69
@IndentlyАй бұрын
Its the age of my maturity
@daisseurАй бұрын
Are you french?
@markramsell454Ай бұрын
So you can't format numbers for your exact country. I don't know python but regex I do. Try txt = "100,009,876.998" x = re.sub("\.", "x", txt) # First sub to not match second sub x = re.sub(",", ".", x) # Second sub to what you want x = re.sub("x", ",", x) # Fix first sub >> 100.009.876,998 Better?