5 Useful F-String Tricks In Python

2024 ж. 10 Ақп.
230 430 Рет қаралды

Here are my top 5 most useful f-string formatting tricks that I use everyday in Python.
▶ Valentine's Day SALE on indently.io:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels

Пікірлер
  • the "=" trick in the f-string is fire.

    @chyldstudios@chyldstudios2 ай бұрын
    • It made my day - I'm gonna test run it in a loop with some random dictionary to see how many cool tricks it can do (like reading current settings) :)

      @m-zurowski@m-zurowski2 ай бұрын
    • ok, my idea didn't work as expected 😅

      @m-zurowski@m-zurowski2 ай бұрын
    • Yeah, completely agree it is amazing

      @dark_brownie@dark_brownie12 күн бұрын
  • Ever since I learned f-strings...I love them.

    @sunwukong6268@sunwukong62683 ай бұрын
    • I wish I had known sooner!!

      @GentleMannOfHats@GentleMannOfHats2 ай бұрын
    • And I love you.... Sorry if I made things awkward... 😬 Oof this awkward isn't it?

      @rickymort135@rickymort1352 ай бұрын
  • About the fourth trick: the f in ".2f" tells it to format as float. You can also do for example ".2e"" which will format the number in scientific format.

    @Zenivo@Zenivo2 ай бұрын
  • I've been using python for about 10 years, and f strings extensively, but never knew that last tip! Game changer!

    @andymitchell2146@andymitchell21462 ай бұрын
    • well, thats cause its only a very recent one (afaik)

      @yash1152@yash11522 ай бұрын
    • @@yash1152it was introduced in 3.8, so a while back

      @eyehear10@eyehear10Ай бұрын
  • This is the first time I have seen someone specify datatype for variables in python, and I honestly loved it. Great tips btw.

    @_Loki__Odinson_@_Loki__Odinson_3 ай бұрын
    • That's the hype for type annotations that I love to see!

      @Indently@Indently3 ай бұрын
    • Not using type annotations should be banned by law

      @Naej7@Naej73 ай бұрын
    • @Naej7 I don't think so, many people choose Python for its simplicity, with the absence of type annotations being one of the key factors. Removing this feature might deter beginners from trying it out. However, as you become more proficient in programming, you may choose to utilize type annotations or when exploring other languages.

      @_Loki__Odinson_@_Loki__Odinson_3 ай бұрын
    • @@_Loki__Odinson_ Type Annotations help a lot, and if adding 5 characters (: int) is too hard at the beginning, then one should give up on programming lmao

      @Naej7@Naej73 ай бұрын
    • ​@@Naej7 Except people don't understand how to use them, so you end up with unnecessarily hard to use APIs. If that's how you feel, why not just use C? 🤦‍♂️

      @edwardcullen1739@edwardcullen17393 ай бұрын
  • The last one is super duper cool!

    @utarasama@utarasama3 ай бұрын
    • RIP the maintainer

      @dcx45@dcx452 ай бұрын
    • ​@@dcx45 he should then watch this video

      @utarasama@utarasama2 ай бұрын
  • Great video! Didn't know about the datetime and debug print ones. Definitely going to use them in the future, though.

    @TheMcSebi@TheMcSebi3 ай бұрын
  • This kind of tips are awesone. We need more 👍

    @krzysiekkrzysiek9059@krzysiekkrzysiek90593 ай бұрын
  • Didn't know about the date/time and equals formatting. Looks like the first one forwards to strftime. Makes things so much more concise and readable.

    @TheJaguar1983@TheJaguar19833 ай бұрын
  • Wow, so many simple things I didn't about... Thank you

    @timegor844@timegor8443 ай бұрын
  • Love your vids man! would love to see a tutorial on cython from you!

    @flashtrack101@flashtrack1012 ай бұрын
  • This is amazing!! thank you for this tutorial!!

    @bashar9200@bashar92002 ай бұрын
  • Thank you for the instructive tips!

    @jaa928@jaa9282 ай бұрын
  • Great video! I missed the bonus tip where you explain that format string calls __format__ on the object being formatted, so you can do your own formatting, like this: class MyData: def __init__(self, a: int, b: int, c: int): self.a = a self.b = b self.c = c def __format__(self, spec): if spec[0] not in self.__dict__: sep = spec[0] l = list(spec[1:]) else: sep = ',' l = list(spec) return sep.join(str(self.__dict__[key]) for key in l) my_var = MyData(a=1, b=2, c=3) assert f"{my_var:cba}" == "3,2,1" assert f"{my_var:-abc}" == "1-2-3"

    @rolandsz8831@rolandsz88312 ай бұрын
  • i love f strings also this is like the 3rd time i come across the = specifier but i keep forgetting its existence and type in the whole thing

    @quekki3666@quekki36663 ай бұрын
    • It's a cool trick for sure!

      @Indently@Indently3 ай бұрын
  • "Simple y bello como un anillo", como diría Neruda; pero además, muy funcional. ¡Muchas gracias!

    @SergioYT2052@SergioYT20522 ай бұрын
  • Finaly! All fstring variations in one film

    @Pawlo370@Pawlo3703 ай бұрын
  • F strings are soo chef kiss

    @mattshu@mattshu3 ай бұрын
  • Loved the last trick!!!

    @viniciomonge3960@viniciomonge3960Ай бұрын
  • For those who didn't know, the last one is called self-documenting expression and was released in Python 3.8

    @UndyingEDM@UndyingEDMАй бұрын
  • Absolutely fantastic and useful video!

    @richsadowsky8580@richsadowsky85802 ай бұрын
  • Nice collection! 💯

    @dipeshsamrawat7957@dipeshsamrawat79573 ай бұрын
  • Love the video I knew some of those but the last one is epic I will be using that from now on .

    @TheKahunas2722000@TheKahunas27220002 ай бұрын
  • Love #5. Thank you.

    @kychemclass5850@kychemclass58502 ай бұрын
  • So cool.. thanks for sharing it. very informative

    @mjhaynavarro@mjhaynavarroАй бұрын
  • Thank you, this went STRAIGHT into my current project. Commas in numbers was one of the next things I was going to look up.

    @cmcdougle@cmcdougle2 ай бұрын
  • Nice and useful tricks for every day programming. I also prefer specifying types of variables, since it makes code better understandable.

    @LittleGnawer@LittleGnawer2 ай бұрын
  • Very nice. Another useful is formatting float as percent: f"{foo:.2%}".

    @BohumirZamecnik@BohumirZamecnik24 күн бұрын
  • This is super cool, I sadly can't think of any usecases in my current project

    @Krullfath@Krullfath3 ай бұрын
  • That last one is sooo useful!

    @catastrophicblues13@catastrophicblues132 ай бұрын
  • Loved it ❤

    @MahdiImeni@MahdiImeni3 ай бұрын
  • Great video.... Thanks a lot😍👍

    @rahulCoding@rahulCoding3 ай бұрын
  • Great work sir❤

    @Angelinajolieshorts@Angelinajolieshorts2 ай бұрын
  • This is pure gold 🥇

    @Anzeljaeg@Anzeljaeg2 ай бұрын
  • Last trick was super cool...

    @karthikkarthik100@karthikkarthik1003 ай бұрын
  • The last one was good!

    @mrjamesflores@mrjamesflores3 ай бұрын
  • thanks for the showcases

    @kinngrimm@kinngrimm2 ай бұрын
  • i knew last one already, but seeing it again made me realise i should try to do this in java too, would have shortened a whole lot of cruft in one program i made.

    @yash1152@yash11522 ай бұрын
  • I like that print(f’{a + b = }’) one at the end. I can think of a few times when I’d use that.

    @daveys@daveys2 ай бұрын
    • Earlier I didn't know it worked on whole expressions, I think it's super cool as well!

      @Indently@Indently2 ай бұрын
  • the last fstring was dope

    @aliwalil4160@aliwalil41603 ай бұрын
  • Great video!

    @griffgruff1@griffgruff12 ай бұрын
  • Thank for nice tricks 😘

    @dark-ghost4132@dark-ghost41323 ай бұрын
  • thanks for your time please make videos about data structure

    @Al_Miqdad_@Al_Miqdad_3 ай бұрын
  • Great video. Thanks

    @ChrisHalden007@ChrisHalden0072 ай бұрын
  • Does datetime have a formating depending on nation? Like we would have already through a login or a whois access to a users current or defined whereabouts or nationality and we would want to have their specific way of reading time provided for them.

    @kinngrimm@kinngrimm2 ай бұрын
  • Trick #2 is neat

    @oldschoolsoldier1634@oldschoolsoldier16343 ай бұрын
  • That last one goes wild

    @Mor3Lif3@Mor3Lif3Ай бұрын
  • Yep, I'm saving this video

    @cheesy_boya@cheesy_boya3 ай бұрын
    • too* 😂😂

      @tolgaflashtr2855@tolgaflashtr28553 ай бұрын
  • These will be useful to me for sure. Here's a comment for the algorithm gods!

    @swolekhine@swolekhine3 ай бұрын
  • Thanks very much

    @SaveCount-bh8tp@SaveCount-bh8tp3 ай бұрын
  • Very nice Thanks

    @sidjay7644@sidjay76443 ай бұрын
  • Круто! Спасибо!

    @Andrey_Fedorov@Andrey_Fedorov2 ай бұрын
  • the thumbnail to this video inspired an idea to use format strings in dictionaries so that a dynamic series of texts can undergo a linear list of mutations. Honestly, I actually need to refine my idea though.

    @0MVR_0@0MVR_03 ай бұрын
  • I always use pyformat. Very easy to understand and pretty nice too. Var = 15 print(“this is my var: {}”.format(var))

    @MechanicusOfficial@MechanicusOfficialАй бұрын
  • Hello @Indently, Can you please explain me, why you use ":" after a variable for ex. n:? Regards.

    @xKiiyoshiix@xKiiyoshiix3 ай бұрын
    • It allows him to specify what type of variable it is. "n: int = " tells anyone reading that it's an integer. I'm glad you asked that though, because I'm an amateur and I'm curious, @Indently is that common practice?

      @matthewbay1978@matthewbay19783 ай бұрын
  • Nice Tricks!

    @Sailesh_Bhoite@Sailesh_Bhoite2 ай бұрын
  • The last one blew my mind

    @sayantanguha1934@sayantanguha19342 ай бұрын
  • I was so stoked when f'{ var = }' was added to Python!! Might be abusing it a bit lol

    @meghanelizondo774@meghanelizondo7742 ай бұрын
  • 9:30 that approach though had the single quotation marks removed, which from a formating pov is cleaner, isn't there a version of the first shorter approach without the quotation marks then printed? (edit: while still being flexible in terms of variable names as mentioned)

    @kinngrimm@kinngrimm2 ай бұрын
  • nice examples

    @aguy9836@aguy98363 ай бұрын
  • Hi! Thanks! Great video! Worth mentioning that the last one does not work on older versions of python3 (I tried it on 3.7.17 and it gives a syntax error).

    @ArtyomKatsap@ArtyomKatsap2 ай бұрын
    • Probably added in a later version. I'd love to know which. Edit: it's called self-documenting expression released in Python 3.8

      @UndyingEDM@UndyingEDMАй бұрын
  • To use scientific notation with integers, you can either do int(2e9) or 2*10**9.

    @mad_vegan@mad_vegan3 ай бұрын
  • May I ask which IDE and development env are you using? Looks so great

    @tudaer@tudaer2 ай бұрын
    • It’s PyCharm

      @meowsqueak@meowsqueak2 ай бұрын
    • @@meowsqueak thanks!

      @tudaer@tudaer2 ай бұрын
  • ooh i like these videos logic magic !

    @noir66146@noir661462 ай бұрын
  • Klasse 😃👍

    @GW-nh9qc@GW-nh9qcАй бұрын
  • What can you do with print(f'{var: >+{x}}') ? The additional + get's printed in front of var but a - doesn't, you can put a # instead of the + and it's not throwing an error, yet doesn't seem to do anything. Letters and other symbols give an error.

    @fg786@fg7863 ай бұрын
  • Good Job

    @Little-bird-told-me@Little-bird-told-me9 күн бұрын
  • My preference is th .format(...) method fo a couple o reasons. I use Micropython a lot and f""" is not or has not been available, for format supports all the styles I like. i8n the string being formatted is not known at development time. Scope, the names using inside the string can be assigned at use time, i.e. in a function the value may be in a variable gmt_time but the string uses a standard name 'time'.

    @acherongoon@acherongoon3 ай бұрын
  • Very nice.

    @artistpw@artistpwАй бұрын
  • Which code editor do you use? It appears to be pycharm. But the ui is different from what I have in windows laptop.

    @MkReman@MkReman3 ай бұрын
    • It’s the new UI. Perhaps you’re still using the legacy UI?

      @meowsqueak@meowsqueak2 ай бұрын
  • My professor who I took intro to Python called the “” ‘right justify and left justify’

    @brycesakal3717@brycesakal37174 күн бұрын
  • Superb

    @ErLakhan@ErLakhanАй бұрын
  • This definitely seems more convenient than it is in js.

    @NickCombs@NickCombs2 ай бұрын
  • Intersting, a large part of the world is using . (period) as a 1000 separator and , (comma) as a decimal point.

    @casperghst42@casperghst42Ай бұрын
  • You make the code easier to read, so you better use the functions of the str class! 🐳

    @iscatafan2959@iscatafan29593 ай бұрын
  • Awesome! I love the '=' and >

    @chrisogonas@chrisogonas2 ай бұрын
  • i dont really know anything about programming or python but im curious. when you do "var:" is the colon part of the variable name? or a requirement for specifying a variable name? if its part of its name, is it to differentiate it from something else?

    @shabadooshabadoo4918@shabadooshabadoo49183 ай бұрын
    • The colon after a variable name is for typing the variable, for example: my_var: str = ‘Hello’ We’re saying that my_var is of type str (string) and has the value ‘Hello’. However, the typing is not necessary and my_var = ‘Hello’ would work just as well. Though, most people would recommend to use type hints

      @AnonHooman@AnonHooman3 ай бұрын
    • @@AnonHooman Well if assigning simple, easy-to-infer data for a variable, I usually do away with type-hinting. Type-hinting is a godsend to mark parameters to a function, preventing hard to trace ValueError or TypeError exceptions later on. I usually don't type hints my variables except when I'm doing unpacking.

      @PanduPoluan@PanduPoluan2 ай бұрын
  • Thank you

    @adeptusmortem@adeptusmortem2 ай бұрын
  • big fan bro from india

    @veeratheking8375@veeratheking83753 ай бұрын
    • Thanks!

      @Indently@Indently3 ай бұрын
  • what theme do you use pycharm

    @mikaelregetz6224@mikaelregetz62242 ай бұрын
  • 3:24 this tip will literally improve my code quality

    @archiemarqx@archiemarqx3 ай бұрын
  • Which editor is that? Looks fresh

    @NC700xLover@NC700xLover2 ай бұрын
  • Fact: You can define custom logic for f'string on your classes and get string after : as argument to __format__

    @Lord2225@Lord22253 ай бұрын
  • This Video was sponsored by me. 💀

    @Smart_Coder7@Smart_Coder73 ай бұрын
  • Don't forget in newer python you can add multiple lines of text by stringing together f strings

    @murphygreen8484@murphygreen84843 ай бұрын
  • Apart from learning about the f condition, I also learned you can declare the data type in python which i have not been doing lol

    @VypeReaper@VypeReaper2 ай бұрын
  • what complier/interpreter does he use?

    @andrewmalani1882@andrewmalani1882Ай бұрын
  • rounding in python .. cool

    @user-hd3pz2ow1b@user-hd3pz2ow1b2 ай бұрын
  • I wish more languages would copy this feature, and that Python would allow you to use variables inside the strings to select formatting options. For my own language, I made all strings f-strings and just have a shorthand where "$var" will stringify the value of `var`, and "${ expr }" will stringify the value of any valid expression. I made it so that format specifiers could use a variable instead of a numeric constant in the string. That way you could pad the output to the terminal dependent on the actual terminal attributes without using a loop. I'm hoping that this methodology negates the need for *printf() functions in my language, because separating the variable from any formatting options on it is error prone, and most of the time people just want to print as is.

    @anon_y_mousse@anon_y_mousse2 ай бұрын
  • For debugging, I recommend the "Icecream" library.

    @rutenowynidoking3593@rutenowynidoking35933 ай бұрын
  • You're cool! 👍

    @-george-1153@-george-1153Ай бұрын
  • Ehem yo bro, are the "int" word after name variable is static type like variable declaring in rust "let num : i32 = 1000000000"?

    @bilatungdulang9708@bilatungdulang97082 ай бұрын
    • No sense, because type sets through assignment. any = 15 If was: any: const = 15 Еlse we have repeat type assignment. any : int = int (15). 🤷‍♂️

      @nadkoch@nadkochАй бұрын
  • Gold!

    @richardnicholas2957@richardnicholas29572 ай бұрын
  • i'm old but i still think everyone should know that most of the f-string stuff comes from C printf/strftime/etc.

    @annieshedden1245@annieshedden12454 күн бұрын
  • In the first example, int variable n assigned a number in scientific notation returns a float number when printed, but no error occurred. In what sense must n be declared a float therefore?

    @midlander8186@midlander81863 ай бұрын
    • It’s not a type declaration, it’s a type hint given as an annotation. Annotations in Python have no effect at run time so no error occurs. They are just hints to a static type checker.

      @meowsqueak@meowsqueak2 ай бұрын
    • Type annotations are just comments, and comments always lie.

      @isodoubIet@isodoubIet2 ай бұрын
  • What editor is this?

    @roshanpandey1498@roshanpandey14982 ай бұрын
  • That last tip is the biggest argument against a debugger; if they wanted you to use it, why did they provide that debug syntax? 🤓

    @Carberra@Carberra2 ай бұрын
  • What does the f prefix do at the beginning of the argument? Are we inserting a blank float?

    @pmenown@pmenown2 ай бұрын
    • Are you talking about the f prefix before the quotes? If yes, then that's "f strings"

      @mudyeet_@mudyeet_2 ай бұрын
    • @@mudyeet_ yeah, like what does an 'f string' even mean? Feel like they missed out on calling it a G string

      @pmenown@pmenown2 ай бұрын
  • Question. Why do you declare the variable with the type? I'm a beginner and I never saw that, it's a good practice?

    @eduardolima5495@eduardolima54953 ай бұрын
    • Type hints or specifying types are good practice, rather than commenting what should be obvious code. It also enables easier linting and test suites. Google "why type hint" ❤

      @alextrebek5237@alextrebek52373 ай бұрын
    • It's called type-hinting. In his example, it doesn't serve much. But in a big program, it will cause the IDE to warn you that you plan on using a variable only to store certain type(s) but you accidentally typed code that assign a different type to it. For instance, say you have result: string = "" Then much later on you assign: result = sorted(some_list) print(result) The IDE will warn you that, "hey, you originally said you're only going to store a string here, but let me warn you, you're about to store a list here." Other than that, Python won't actually error out there.

      @PanduPoluan@PanduPoluan3 ай бұрын
    • Another example purpose: You assign the result of a function that _declares_ it will return a list of floats def some_func() -> list[float]: ... rslt_list = some_func() Then you do this: print(", ".join(rslt_list)) The IDE will warn you that the str.join() function requires a list of str, but you're calling it with a list of floats. In this case, if you don't heed the warning, your program will raise an error at that point (because of .join()'s requirement).

      @PanduPoluan@PanduPoluan3 ай бұрын
    • Again, in all case, you're only given a hint that _probably_ something is not quite right. It still won't change Python into a statically-typed language. Just another tool to help a Python Programmer prevent errors due to Type Mismatch.

      @PanduPoluan@PanduPoluan3 ай бұрын
    • @@PanduPoluan bro! Thanks for the answer!! Super detailed!!

      @eduardolima5495@eduardolima54953 ай бұрын
  • Hi, if I have a number 1234.5678, how do I use a combination of , separators make it 2 decimal places so I get 1,234.56?

    @philluvschips3787@philluvschips37872 ай бұрын
KZhead