5 More Useful F-String Tricks In Python
HTML-код
- Опубликовано: 1 июн 2024
- Here are 5 more useful f-string tricks that you can use in Python!
Previous video: • 5 Useful F-String Tric...
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Learning Python made simple
00:05 Intro
00:33 Scientific notation
01:41 Specifiers as variables
03:38 "fr" strings
05:28 Quick debugging (continued)
07:14 !s !r !a
09:23 What do you think?
Hello everyone, another life hack for those of you who find the explanations to be a bit slow, is to set the video speed to something faster like 1.5x or 2x (I edit at 2x usually so watching these feels incredibly slow xD).
Otherwise I wish you all a great weekend and happy coding! :)
If you press the ? key, you will get the shortcuts - my favorites are: j and l ... which jumps 10s and there are the cursor keys left and right which jumps 5s
I'm learning to "do a RUclips"!
By the way, a better path formatting option is pathlib. For example, it makes sure the slash is correct.
You beat me to it... it's a really nice library, and PyCharm gives me warnings for using os.path.join.
And an even better one is os.path, which processes path strings just like Pathlib but without using a whole Path class
Or just use forward slashes only lol
@@K0D0R0 but then your code is not portable on Windows, that's a waste. The os module is built-in python, you have it installed anyway, so why not use it ? Moreover, and most importantly actually, with it you can do much more than just slashing right, you can test the existence and the type of the data pointed by the path, and even create files and directories at given paths automatically from inside your code !
You can use forward slashes "C:/Windows" or path.join() on an array:
>>> import os
>>> os.path.join('C:', 'Windows')
'C:/Windows'
>>> os.getenv('OS')
'Windows_NT'
override __format__(format_spec: str) on the class and you can do anything you want, like: f"{something:customformat}"
Yeah, finally the true advice of them all, any class can benefit from f-strings formatter different ways, you just have to go read the class at the __format__ method to know what's possible
The first thing I learned from this video, was that you can use underscores in numbers.
It's nice how you keep these topics short and concise. I find myself going catatonic on long videos about the more advanced Python topics.
4:26 you can actually still use forward slashes in Windows. Python will automatically do the conversion under the hood.
Python isn't doing the conversion. The Windows APIs actually accept forward-slashes! It works everywhere but the native file dialogs and cmd.exe.
NEVER knew about the F and R together thanks so much!
working with jupyter notebooks and lots of paths everyday, I never knew about the fr-string! That will surely come in super handy!
Another neat raw string trick is r vs R. Most IDEs will syntax highlight a lower r raw string as regex and an upper R raw string as a pure raw string. Doesn't matter to the interpreter.
For trick #3, paths, at this point, I would think people would be using pathlib.Path:
from pathlib import Path
my_folder = 'python_code'
my_path = Path.cwd() / 'scripts' / my_folder
which should work regardless of OS.
agreed! better use something designed for the task instead of tinkering with strings
f-string blows my mind every time I learn more about it
Super cool! Looking forward to see the part 3
The way you explain things is really exceptional. Thank you for your content!
This was great, I've been using Python for almost 2 decades and I only knew 1 of those tricks.
Awesome. Thx and need more 👌
excellent! I've done Python for decades and didn't know all of these. Subscribed.
I often define a date format at the top of my code to use in strftime. Now with f-strings, this will be much simpler going forward as I uplift code from old servers with out-dated python versions.
Why are you explicitly define type in initialization?
any_var = 'fmt'. In with case type being installed through assignment.
Really useful!
I saw this video and on the same day the raw string came SO handy ! using f" ...
" broke something in my CI/CD, and using fr"" solved it !
Very nice 🙂❤
awesome!
Actually, you don't need to use backslash even on Windows! Forward slash works fine, except in a few limited contexts, like the native file dialogs, or cmd.exe. The filesystem APIs accept forward slash. Also, use the pathlib library rather than constructing strings. The / operator works on Path objects, so you can add levels without string manipulation.
So useful
Is that the Python we Know?
perfect,... ❤ what pep version you use?
so cool!
Thanks.
Another good one! My favourite is the one about nesting this time
Believe or not but I called my family to say that one of my favourite YT authors loved my comment- You made my day :)
Sorry, I just got to say it.
Firstly, that’s just sad.
Secondly, Indently likes most of the comments.
@@K0D0R0 small acts of happiness defines our lifes, I am lookint for a reason to smile. Not the opposite, the fact he likes most of his viewers comments makes me happy even more and likes him even more for engaging with community, all the best my friend :)
Don’t mind him Robert, what he said was absolutely rude and I hope he grows up eventually because that just wasn’t a nice thing to say, and shouldn’t have been mentioned at all.
I read every comment and appreciate every comment, I don’t always have time to respond to all of them, so sometimes the best I can do is live a little heart.
Thank you for your positive energy Robert :)
@@Indently truth hurts? Never would have thought.
Unless he is 10 y.o., that’s indeed sad. Hope Robert finds actual happiness.
Thanks
5:10 rm -rf"{formatcomputer()}"
Regarding paths just use pathlib.
How did you get tthat banana symbol graphic ?
Love the hacks Federico! 🔥If anyone’s looking for more Python tutorials, we’ve released Loguru logging, task scheduling, and more to help the community too 💪
Great tips. Thanks. I did run into one interesting issue: say I have a function f(n), and a variable x whose value is 10, and say f(x) returns 20, so I want to print out "f(10)=20", is there anyway to achieve that with f-string in the simplest way?
f(x=10) could be a possible solution
Which IDE are you using?
Regarding the file names, slashes work just fine in Windows. Don’t know if it is an official or unofficial feature though.
Forward slashes work fine in Win32. But they screw up Windows's benighted command interpreter, which uses / as the option introducer (instead of the more civilized hyphen, as in *nix and MacOS).
@@davidagnew8465 yes that’s right but I use powershell only where slashes also work. It’s very useful when you are using Remote Desktop and have keyboard issues.
Is there a way to combine padding around an integer with thousands separators?
Something like: print(f"|{next(primes):,_^20}|")
Where my intension is to have the _ as the fill character and the number shown using the , as a thousands separator.
Wellllp.... never mind. Shortly after asking I tried one more thing..... And this worked:
print(f"|{next(primes):_^20,}|")
Suggestion for a video topic: when using f-strings is not the best idea. Hint: logging.
At trick 3, how do i write "{}" as characters in the fr string?
You should escape both like this:
escaped_curlies = "curly brackets are \{ and \}"
Do you do anything with Django? Im currently trying to learn it and would love to get Django content from you.
Personally I don't because I hate doing anything that's web dev related. But maybe I'll team up with someone who enjoys doing it in the near future :)
@@Indently Yes please!
I feel like beginners watching this would definitely have benefitted from you explaining that float addition result. It makes no sense if you just pretend it's normal.
he has other videos explaining floats
What IDE is this?
f-strings are a mini language within Python. As are regex and function header docstrings. What other mini-languages do exist within Python? AFAIK, SQL is not one of them. Some consider tuple and dict destructurings another one ;)
Why would you classify regex as a Python minilanguage? Both regex and SQL have an existence completely independent of Python, whereas f-strings are inextricably coupled to the outer language (e.g., the !s and !r format operators being shortcuts to str and repr).
@@davidagnew8465 Well, regex gave rise to r'' "raw" strings and the f'' "formatting" language is ultimatively heritage of Fortran format specifiers. I only abstract and call all of this "mini languages".
@@falklumolanguage doesnt sound like the best term, regex isn't a language but rather a parser where you provide a parser configuration string
it's more like it influences pythons syntax, so maybe python influences is a better term?
@@thomaseb97 regex is a language, nobody would debate that.
How do you enter emojis in python code? News to me
5:14 Ah yes, France-String 🥖🥐
The embedded formatter from another string just sounds like a security issue waiting to happen.
I only .format one
"for real" string
The saddest part is that when you use Python every day to produce code for your client, like me, you are just down in the rut and don't spend enough time learning these features. Even though they would save you time, make your code better, and long term make you less busy. You're too busy to become less busy! 😭😭😭
fraw string is smth new for me
fr (for real)
I don't get it. Isn't f'{name !s}' exactly the same as f'{name}'?
Bob & 'Bob' . !s helps you get rid of the single-quote while printing
@@VijayGandhinagar!s is the default. !r would add the quotation marks
@VijayGandhinagar print(name) also doesn't show quotes so the !s seems useless for strings.
Sorry for the confusion. Here is what I was referring to.. give it a try..
name = 'Bob'
print(f'{name = }')
print(f'{name = !s}')
I got ..
name = 'Bob'
name = Bob
'
5:11 they try to conceal their experience with the "rf". Poor soul
If only you could replace the curly brackets with something else... So annoying when putting JavaScript in streamlit or smth
If you do this a lot, you definitely should create a JavaScript string class that escapes curly brackets and takes something else as a marker of formatted strings.
@@RedHair651 Yeah I should do that actually... How exactly you do that never heard about this
In Python, "tricks" are generally seen as a Bad thing.
Bobnana.
I prefer rf. It makes me feel of Russian Federation
Why is 1.62e9 a float. We just saw that it is one billion six hundred twenty million, which is definitely an integer when it is not written in words like I did but rather in numerals.
To allow real numbers as well I think
You can write like
1.602e-19 which is definitely a real number
wait... what! he is french?! he must be punished!!
instructions unclear, rm-rf / bombed
fr!