5 Useful F-String Tricks In Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ก.พ. 2025

ความคิดเห็น • 369

  • @chyldstudios
    @chyldstudios 11 หลายเดือนก่อน +496

    the "=" trick in the f-string is fire.

    • @m-zurowski
      @m-zurowski 11 หลายเดือนก่อน +9

      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-zurowski 11 หลายเดือนก่อน +18

      ok, my idea didn't work as expected 😅

    • @dark_brownie
      @dark_brownie 9 หลายเดือนก่อน +2

      Yeah, completely agree it is amazing

  • @Zenivo
    @Zenivo 11 หลายเดือนก่อน +72

    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.

  • @andymitchell2146
    @andymitchell2146 11 หลายเดือนก่อน +88

    I've been using python for about 10 years, and f strings extensively, but never knew that last tip! Game changer!

    • @yash1152
      @yash1152 11 หลายเดือนก่อน +4

      well, thats cause its only a very recent one (afaik)

    • @eyehear10
      @eyehear10 10 หลายเดือนก่อน

      @@yash1152it was introduced in 3.8, so a while back

  • @sunwukong6268
    @sunwukong6268 11 หลายเดือนก่อน +158

    Ever since I learned f-strings...I love them.

    • @GentleMannOfHats
      @GentleMannOfHats 11 หลายเดือนก่อน

      I wish I had known sooner!!

    • @rickymort135
      @rickymort135 11 หลายเดือนก่อน +2

      And I love you....
      Sorry if I made things awkward... 😬
      Oof this awkward isn't it?

  • @_Loki__Odinson_
    @_Loki__Odinson_ 11 หลายเดือนก่อน +236

    This is the first time I have seen someone specify datatype for variables in python, and I honestly loved it.
    Great tips btw.

    • @Indently
      @Indently  11 หลายเดือนก่อน +52

      That's the hype for type annotations that I love to see!

    • @Naej7
      @Naej7 11 หลายเดือนก่อน +11

      Not using type annotations should be banned by law

    • @_Loki__Odinson_
      @_Loki__Odinson_ 11 หลายเดือนก่อน +28

      @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.

    • @Naej7
      @Naej7 11 หลายเดือนก่อน +5

      @@_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

    • @edwardcullen1739
      @edwardcullen1739 11 หลายเดือนก่อน +15

      ​@@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? 🤦‍♂️

  • @utarasama
    @utarasama 11 หลายเดือนก่อน +40

    The last one is super duper cool!

    • @dcx45
      @dcx45 11 หลายเดือนก่อน

      RIP the maintainer

    • @utarasama
      @utarasama 11 หลายเดือนก่อน

      ​@@dcx45 he should then watch this video

  • @rolandsz8831
    @rolandsz8831 11 หลายเดือนก่อน +6

    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"

  • @BohumirZamecnik
    @BohumirZamecnik 9 หลายเดือนก่อน +8

    Very nice. Another useful is formatting float as percent: f"{foo:.2%}".

  • @TheJaguar1983
    @TheJaguar1983 11 หลายเดือนก่อน +11

    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.

  • @TheMcSebi
    @TheMcSebi 11 หลายเดือนก่อน +5

    Great video! Didn't know about the datetime and debug print ones. Definitely going to use them in the future, though.

  • @im_a_surfingdoggo
    @im_a_surfingdoggo 11 หลายเดือนก่อน +5

    Thank you, this went STRAIGHT into my current project. Commas in numbers was one of the next things I was going to look up.

  • @KinkyJalepeno
    @KinkyJalepeno 7 หลายเดือนก่อน +1

    This series of vids are the best on youtube - keep it going please, best sub ever.

  • @enriqueDFTL
    @enriqueDFTL 7 หลายเดือนก่อน +1

    I never use anything other than f-strings when printing and these tips are great. Going to use them!

  • @SergioYT2052
    @SergioYT2052 11 หลายเดือนก่อน +2

    "Simple y bello como un anillo", como diría Neruda; pero además, muy funcional. ¡Muchas gracias!

  • @mrinmoybanik5598
    @mrinmoybanik5598 7 วันที่ผ่านมา

    wow I had no idea about that last debugging trick!! This was soo helpful, thanks!

  • @krzysiekkrzysiek9059
    @krzysiekkrzysiek9059 11 หลายเดือนก่อน +5

    This kind of tips are awesone. We need more 👍

  • @mattshu
    @mattshu 11 หลายเดือนก่อน +4

    F strings are soo chef kiss

  • @daveys
    @daveys 11 หลายเดือนก่อน +2

    I like that print(f’{a + b = }’) one at the end. I can think of a few times when I’d use that.

    • @Indently
      @Indently  11 หลายเดือนก่อน +1

      Earlier I didn't know it worked on whole expressions, I think it's super cool as well!

  • @alfredo.onyoutube
    @alfredo.onyoutube 3 หลายเดือนก่อน +1

    Didn't know the last one! Thanks 👍

  • @mad_vegan
    @mad_vegan 11 หลายเดือนก่อน +5

    To use scientific notation with integers, you can either do int(2e9) or 2*10**9.

  • @acherongoon
    @acherongoon 11 หลายเดือนก่อน

    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'.

  • @richsadowsky8580
    @richsadowsky8580 11 หลายเดือนก่อน +1

    Absolutely fantastic and useful video!

  • @LittleGnawer
    @LittleGnawer 11 หลายเดือนก่อน

    Nice and useful tricks for every day programming. I also prefer specifying types of variables, since it makes code better understandable.

  • @masoudfarrokhy6926
    @masoudfarrokhy6926 หลายเดือนก่อน +1

    God bless you brother

  • @xKiiyoshiix
    @xKiiyoshiix 11 หลายเดือนก่อน +1

    Hello @Indently,
    Can you please explain me, why you use ":" after a variable for ex. n:?
    Regards.

    • @matthewbay1978
      @matthewbay1978 11 หลายเดือนก่อน

      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?

  • @flashtrack101
    @flashtrack101 11 หลายเดือนก่อน +1

    Love your vids man! would love to see a tutorial on cython from you!

  • @mjhaynavarro
    @mjhaynavarro 10 หลายเดือนก่อน

    So cool.. thanks for sharing it. very informative

  • @quekki3666
    @quekki3666 11 หลายเดือนก่อน +14

    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

    • @Indently
      @Indently  11 หลายเดือนก่อน +1

      It's a cool trick for sure!

  • @jaa928
    @jaa928 11 หลายเดือนก่อน

    Thank you for the instructive tips!

  • @Pawlo370
    @Pawlo370 11 หลายเดือนก่อน +1

    Finaly! All fstring variations in one film

  • @timegor844
    @timegor844 11 หลายเดือนก่อน

    Wow, so many simple things I didn't about... Thank you

  • @tudaer
    @tudaer 11 หลายเดือนก่อน

    May I ask which IDE and development env are you using? Looks so great

    • @meowsqueak
      @meowsqueak 11 หลายเดือนก่อน +1

      It’s PyCharm

    • @tudaer
      @tudaer 11 หลายเดือนก่อน

      @@meowsqueak thanks!

  • @viniciomonge3960
    @viniciomonge3960 10 หลายเดือนก่อน

    Loved the last trick!!!

  • @kinngrimm
    @kinngrimm 11 หลายเดือนก่อน

    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)

  • @wceez
    @wceez 3 หลายเดือนก่อน +1

    Python pointing out you’re high. It’s gonna be a game changer when that module drops 😂😂😂 3:50

  • @bashar9200
    @bashar9200 11 หลายเดือนก่อน

    This is amazing!! thank you for this tutorial!!

  • @elbadrey
    @elbadrey 6 หลายเดือนก่อน

    Honestly l 💖 your style explanation, and knowledge.
    How do you get this information, what books you read, or perfect roadmap with reference to follow.

  • @yash1152
    @yash1152 11 หลายเดือนก่อน

    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.

  • @TheKahunas2722000
    @TheKahunas2722000 11 หลายเดือนก่อน

    Love the video I knew some of those but the last one is epic I will be using that from now on .

  • @alisajjad2478
    @alisajjad2478 8 หลายเดือนก่อน

    Thanks for the tips. The last trick is amazing

  • @kinngrimm
    @kinngrimm 11 หลายเดือนก่อน

    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.

  • @rahulCoding
    @rahulCoding 11 หลายเดือนก่อน

    Great video....
    Thanks a lot😍👍

  • @MechanicusOfficial
    @MechanicusOfficial 9 หลายเดือนก่อน

    I always use pyformat. Very easy to understand and pretty nice too. Var = 15
    print(“this is my var: {}”.format(var))

  • @UndyingEDM
    @UndyingEDM 9 หลายเดือนก่อน +1

    For those who didn't know, the last one is called self-documenting expression and was released in Python 3.8

  • @casperghst42
    @casperghst42 9 หลายเดือนก่อน

    Intersting, a large part of the world is using . (period) as a 1000 separator and , (comma) as a decimal point.

  • @pmenown
    @pmenown 11 หลายเดือนก่อน

    What does the f prefix do at the beginning of the argument? Are we inserting a blank float?

    • @mudyeet_
      @mudyeet_ 11 หลายเดือนก่อน

      Are you talking about the f prefix before the quotes? If yes, then that's "f strings"

    • @pmenown
      @pmenown 11 หลายเดือนก่อน

      @@mudyeet_ yeah, like what does an 'f string' even mean? Feel like they missed out on calling it a G string

    • @sophiophile
      @sophiophile หลายเดือนก่อน

      An f string is a formatted string, where you can put references to variables/objects by wrapping them in curly braces, instead of having to concatenate them- especially since Python strings are immutable.
      What he is showing off is some of the special extra features available when you follow up the variable/object with a colon to implement some special manipulation of the final string on top of the substitution.

  • @karthikkarthik100
    @karthikkarthik100 11 หลายเดือนก่อน +2

    Last trick was super cool...

  • @asakhhh
    @asakhhh 4 หลายเดือนก่อน

    adding to the note that only underscores and commas can be used: I think we can just apply character replacing to the resulting string

  • @catastrophicblues13
    @catastrophicblues13 11 หลายเดือนก่อน

    That last one is sooo useful!

  • @archiemarqx
    @archiemarqx 11 หลายเดือนก่อน

    3:24 this tip will literally improve my code quality

  • @dipeshsamrawat7957
    @dipeshsamrawat7957 11 หลายเดือนก่อน +1

    Nice collection! 💯

  • @kychemclass5850
    @kychemclass5850 11 หลายเดือนก่อน

    Love #5. Thank you.

  • @meghanelizondo774
    @meghanelizondo774 11 หลายเดือนก่อน

    I was so stoked when f'{ var = }' was added to Python!! Might be abusing it a bit lol

  • @SobTim-eu3xu
    @SobTim-eu3xu 7 หลายเดือนก่อน

    First is fire
    Second is fire(unless filling, I know this)
    Third is like in C#, but without f string
    Fourth I know, and also like in C#(unless ,.3f, this is fire)
    Fifth is fire, this is why I live python)
    1year+ of python)
    I use it in cryptography, and numerical methods)

  • @anon_y_mousse
    @anon_y_mousse 11 หลายเดือนก่อน

    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.

  • @shabadooshabadoo4918
    @shabadooshabadoo4918 11 หลายเดือนก่อน

    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?

    • @PanduPoluan
      @PanduPoluan 11 หลายเดือนก่อน +1

      @@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.

  • @Anzeljaeg
    @Anzeljaeg 11 หลายเดือนก่อน

    This is pure gold 🥇

  • @ArtyomKatsap
    @ArtyomKatsap 11 หลายเดือนก่อน

    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).

    • @UndyingEDM
      @UndyingEDM 9 หลายเดือนก่อน +1

      Probably added in a later version. I'd love to know which. Edit: it's called self-documenting expression released in Python 3.8

  • @ChrisHalden007
    @ChrisHalden007 11 หลายเดือนก่อน

    Great video. Thanks

  • @yelircaasi
    @yelircaasi 10 หลายเดือนก่อน

    Which editor is that? Looks fresh

  • @eloyam9973
    @eloyam9973 4 หลายเดือนก่อน

    The last one was 🔥

  • @Krullfath
    @Krullfath 11 หลายเดือนก่อน

    This is super cool, I sadly can't think of any usecases in my current project

  • @swolekhine
    @swolekhine 11 หลายเดือนก่อน +2

    These will be useful to me for sure. Here's a comment for the algorithm gods!

  • @0MVR_0
    @0MVR_0 11 หลายเดือนก่อน

    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.

  • @All_u_need_channel
    @All_u_need_channel 11 หลายเดือนก่อน

    Great work sir❤

  • @cheesy_boya
    @cheesy_boya 11 หลายเดือนก่อน +3

    Yep, I'm saving this video

  • @griffgruff1
    @griffgruff1 11 หลายเดือนก่อน

    Great video!

  • @NickCombs
    @NickCombs 11 หลายเดือนก่อน +1

    This definitely seems more convenient than it is in js.

  • @MahdiImeni
    @MahdiImeni 11 หลายเดือนก่อน

    Loved it ❤

  • @murphygreen8484
    @murphygreen8484 11 หลายเดือนก่อน +1

    Don't forget in newer python you can add multiple lines of text by stringing together f strings

  • @chrisogonas
    @chrisogonas 11 หลายเดือนก่อน

    Awesome! I love the '=' and >

  • @sidjay7644
    @sidjay7644 11 หลายเดือนก่อน

    Very nice
    Thanks

  • @Lord2225
    @Lord2225 11 หลายเดือนก่อน +2

    Fact: You can define custom logic for f'string on your classes and get string after : as argument to __format__

  • @dark-ghost4132
    @dark-ghost4132 11 หลายเดือนก่อน

    Thank for nice tricks 😘

  • @eduardolima5495
    @eduardolima5495 11 หลายเดือนก่อน

    Question. Why do you declare the variable with the type? I'm a beginner and I never saw that, it's a good practice?

    • @alextrebek5237
      @alextrebek5237 11 หลายเดือนก่อน

      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" ❤

    • @PanduPoluan
      @PanduPoluan 11 หลายเดือนก่อน +1

      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
      @PanduPoluan 11 หลายเดือนก่อน +1

      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
      @PanduPoluan 11 หลายเดือนก่อน +1

      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.

    • @eduardolima5495
      @eduardolima5495 11 หลายเดือนก่อน +1

      @@PanduPoluan bro! Thanks for the answer!! Super detailed!!

  • @arduous222
    @arduous222 หลายเดือนก่อน

    Everybody thinking comma vs period for readibility separator situation is bad.
    Meanwhile in East Asia: comma is used for readibility for every 4 digits contrary to 3 in European worlds. But sometimes every 3 digits. Now it is all mixed and everyone gave up and started counting the digits.

  • @eugenepark
    @eugenepark 7 หลายเดือนก่อน

    Is it possible to combine f"{n:,}" and f"{n:20}" somehow? or are they an exclusive or

    • @AlexV6
      @AlexV6 5 หลายเดือนก่อน

      Yes, you should use 'nested f-strings'.

  • @paternyao
    @paternyao 11 หลายเดือนก่อน

    What is this IDE? The console right below is so cool

    • @Indently
      @Indently  11 หลายเดือนก่อน

      PyCharm

  • @kinngrimm
    @kinngrimm 11 หลายเดือนก่อน

    in the first example, do you know what decimal points wouldn't work?

  • @midlander8186
    @midlander8186 11 หลายเดือนก่อน

    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?

    • @meowsqueak
      @meowsqueak 11 หลายเดือนก่อน +1

      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.

    • @isodoubIet
      @isodoubIet 11 หลายเดือนก่อน

      Type annotations are just comments, and comments always lie.

  • @Al_Miqdad_
    @Al_Miqdad_ 11 หลายเดือนก่อน

    thanks for your time
    please make videos about data structure

  • @sayantanguha1934
    @sayantanguha1934 11 หลายเดือนก่อน

    The last one blew my mind

  • @aliwalil4160
    @aliwalil4160 11 หลายเดือนก่อน

    the last fstring was dope

  • @bitelogger
    @bitelogger 6 หลายเดือนก่อน

    Hi, please which IDE are you using on this video?

  • @VypeReaper
    @VypeReaper 11 หลายเดือนก่อน

    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

  • @Sailesh_Bhoite
    @Sailesh_Bhoite 11 หลายเดือนก่อน

    Nice Tricks!

  • @nuynobi
    @nuynobi 8 หลายเดือนก่อน +4

    Only the last one is specific to f-strings though, right? The rest are all just general string formatting techniques. Good tips nonetheless.

    • @itsmeashbeel9175
      @itsmeashbeel9175 4 หลายเดือนก่อน

      No I believe you need to use fstring for all examples. You can tell by the use of code in curly brackets. In other strings the curly brackets won't do anything code related

    • @nuynobi
      @nuynobi 4 หลายเดือนก่อน

      @@itsmeashbeel9175 Negatory. He demonstrates them using fstrings but they need not be. All but one of these tips can be used to format a regular string with its `format` method (ie 'new style' string formatting which uses curly braces to indicate replacements, just like fstrings do).

  • @artistpw
    @artistpw 10 หลายเดือนก่อน

    Very nice.

  • @kinngrimm
    @kinngrimm 11 หลายเดือนก่อน

    thanks for the showcases

  • @Carberra
    @Carberra 11 หลายเดือนก่อน

    That last tip is the biggest argument against a debugger; if they wanted you to use it, why did they provide that debug syntax? 🤓

  • @SaveCount-bh8tp
    @SaveCount-bh8tp 11 หลายเดือนก่อน

    Thanks very much

  • @mrjamesflores
    @mrjamesflores 11 หลายเดือนก่อน

    The last one was good!

  • @andrewmalani1882
    @andrewmalani1882 9 หลายเดือนก่อน

    what complier/interpreter does he use?

  • @vedantkanoujia
    @vedantkanoujia 8 หลายเดือนก่อน

    you helped me for spaces , I used it in list with \t

  • @Little-bird-told-me
    @Little-bird-told-me 9 หลายเดือนก่อน

    Good Job

  • @Mor3Lif3
    @Mor3Lif3 10 หลายเดือนก่อน

    That last one goes wild

  • @MkReman
    @MkReman 11 หลายเดือนก่อน

    Which code editor do you use? It appears to be pycharm. But the ui is different from what I have in windows laptop.

    • @meowsqueak
      @meowsqueak 11 หลายเดือนก่อน

      It’s the new UI. Perhaps you’re still using the legacy UI?

  • @bilatungdulang9708
    @bilatungdulang9708 11 หลายเดือนก่อน

    Ehem yo bro, are the "int" word after name variable is static type like variable declaring in rust "let num : i32 = 1000000000"?

    • @nadkoch
      @nadkoch 10 หลายเดือนก่อน

      No sense, because type sets through assignment.
      any = 15
      If was:
      any: const = 15
      Еlse we have repeat type assignment.
      any : int = int (15). 🤷‍♂️

  • @rutenowynidoking3593
    @rutenowynidoking3593 11 หลายเดือนก่อน

    For debugging, I recommend the "Icecream" library.

  • @iscatafan2959
    @iscatafan2959 11 หลายเดือนก่อน

    You make the code easier to read, so you better use the functions of the str class! 🐳