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.
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
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
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
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('_', '.')}'.
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"}"}")
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}}'
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.
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
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 "
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
@ 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.
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.
@@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
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.
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.
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
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
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.
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.
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?
you can also change bases in F strings:
>>> f'{4:0b}'
'100'
>>>
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.
15:05 Left alignment is the default for strings, but right alignment is the default for numbers.
Another nice formatted for numbers
num = 123.4566
print(f‘{num}:.5g’)
is 123.46
nice way to print a certain significant figures
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
15:34 was completely new to me!
I've been coding Python for years, and this is so helpful!
excellent, now i need to do some edits to one of my programs
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
Thanks for sharing, I read a few examples in the comments and it looks useful!
Also useful to generate HTML
Thanks!
Thank you! :)
Dynamic spacing saved my life, thank you very much. At 15:30 for anyone wondering.
Raw strings are used extensively for regex patterns, so French strings (love that by the way!) are great if you need variable regex patterns
Very cool, thanks for all the info
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
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('_', '.')}'.
You don't need a nested f-string to do that. This works just fine:
`f"{big_num:_}".replace("_", ".")`
@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().
Great tricks! The last one is superb.
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"}"}")
Awesome example!🤩
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}}'
This is so useful !
Every F-String in python is censored.
Great video 🎉🎉
Thank you 😊
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.
They are pythonic
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.
How can something built into python not be pythonic
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
16:01 you know pycharm has an block edit mode? Click middle mouse button and drag over all 20, then paste
More reasons to love python!!
The fr string is pretty useful to write regular expressions
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
Thank you.
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 "
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...
time stamp? If you're talking dunder format, you can _always_ call super.
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
@ 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.
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.
@@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
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.
❤❤
Please, I would like to know the name of the theme you use in PyCharm😊. Thank you
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.
FYI most of these tips are not specific to f-strings and will work with normal string formatting, ie str.format().
That is because f string is a short cut for this function (specially since the revision in 3.12) right?
@oida10000 Could be. I never really thought about how f-strings work under the hood.
… when you first hear “dunder” and think it’s a name; then realize it’s “d(ouble)-under(score)”….
Thanks for clarifying this for me!
Are all these tricks possible when using multi-lined f-strings?
There might be some complications which I’m unaware of, but for the most part yes.
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.
Unfortunately floating-point numbers don't really have a way of remembering the amount of decimals like that. You'd need a separate variable
@@bronkolie it's a text file. He wrote
p = .5678
which should be:
p = 0.5678
@@DrDeuteron sorry, I thought you meant the last zero like in 0.80 vs 0.8
What is the risk from doing this? I've seen it regularly but this is the first I've heard of it being bad
What ide is this?
He mentioned PyCharm
Can someone explain why is name and age defined that way with : instead of using "="?
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
@@indyplaygames3066 so why not just type name = 'indy'? It is obviously a string and the variable is defined ? Is it the same?
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
@@fernandezguille Thank you!
The first example is broken as the name was used as a literal string
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.
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.
Isn't this a repost?
No, I stated that this was a complete video in the intro.
Me first
You could've just called it F-String Theory
Thank you for the suggestion
quick maths lol
Why are they called fvck strings?
age = 69
Its the age of my maturity
Are you french?
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?
Did ChatGPT generate this?
Better:
txt.translate(dict(zip(map(ord, ',_.'), '..,')))