Every F-String Trick In Python Explained

แชร์
ฝัง
  • เผยแพร่เมื่อ 28 ธ.ค. 2024

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

  • @U.k358
    @U.k358 หลายเดือนก่อน +52

    you can also change bases in F strings:
    >>> f'{4:0b}'
    '100'
    >>>

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

    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.

  • @mrab4222
    @mrab4222 หลายเดือนก่อน +13

    15:05 Left alignment is the default for strings, but right alignment is the default for numbers.

  • @lordstevenson9619
    @lordstevenson9619 หลายเดือนก่อน +20

    Another nice formatted for numbers
    num = 123.4566
    print(f‘{num}:.5g’)
    is 123.46
    nice way to print a certain significant figures

  • @SaschaMarkus
    @SaschaMarkus 29 วันที่ผ่านมา +4

    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

  • @TheFerdi265
    @TheFerdi265 25 วันที่ผ่านมา +2

    15:34 was completely new to me!
    I've been coding Python for years, and this is so helpful!

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

    excellent, now i need to do some edits to one of my programs

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

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

      Thanks for sharing, I read a few examples in the comments and it looks useful!

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

      Also useful to generate HTML

  • @glg216
    @glg216 27 วันที่ผ่านมา

    Thanks!

    • @Indently
      @Indently  27 วันที่ผ่านมา

      Thank you! :)

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

    Dynamic spacing saved my life, thank you very much. At 15:30 for anyone wondering.

  • @ROldford
    @ROldford 22 วันที่ผ่านมา

    Raw strings are used extensively for regex patterns, so French strings (love that by the way!) are great if you need variable regex patterns

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

    Very cool, thanks for all the info

  • @mightyhelper8336
    @mightyhelper8336 18 วันที่ผ่านมา

    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

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

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

      You don't need a nested f-string to do that. This works just fine:
      `f"{big_num:_}".replace("_", ".")`

    • @elfoyoutube6039
      @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().

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

    Great tricks! The last one is superb.

  • @rsvdark_main
    @rsvdark_main 22 วันที่ผ่านมา +1

    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"}"}")

  • @Dubbidu
    @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}}'

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

    This is so useful !

  • @GoodWill-s8j
    @GoodWill-s8j หลายเดือนก่อน +5

    Every F-String in python is censored.

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

    Great video 🎉🎉

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

    Thank you 😊

  • @DrDeuteron
    @DrDeuteron หลายเดือนก่อน +19

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

      They are pythonic

    • @RandomWolfPrinting
      @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
      @hedwig7s 29 วันที่ผ่านมา +5

      How can something built into python not be pythonic

    • @p1geon45
      @p1geon45 19 วันที่ผ่านมา +1

      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

  • @user-us8th9zn1g
    @user-us8th9zn1g หลายเดือนก่อน +1

    16:01 you know pycharm has an block edit mode? Click middle mouse button and drag over all 20, then paste

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

    More reasons to love python!!

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

    The fr string is pretty useful to write regular expressions

  • @TRADINGPULSE397
    @TRADINGPULSE397 26 วันที่ผ่านมา

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

    Thank you.

  • @schwingedeshaehers
    @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 "

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

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

      time stamp? If you're talking dunder format, you can _always_ call super.

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

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

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

  • @Dzjur.
    @Dzjur. 23 วันที่ผ่านมา +2

    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
    @Ismail_Hassan-77 27 วันที่ผ่านมา

    ❤❤
    Please, I would like to know the name of the theme you use in PyCharm😊. Thank you

  • @uplink-on-yt
    @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.

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

    FYI most of these tips are not specific to f-strings and will work with normal string formatting, ie str.format().

    • @oida10000
      @oida10000 29 วันที่ผ่านมา

      That is because f string is a short cut for this function (specially since the revision in 3.12) right?

    • @nuynobi
      @nuynobi 28 วันที่ผ่านมา

      @oida10000 Could be. I never really thought about how f-strings work under the hood.

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

    … when you first hear “dunder” and think it’s a name; then realize it’s “d(ouble)-under(score)”….

    • @fernandezguille
      @fernandezguille 28 วันที่ผ่านมา

      Thanks for clarifying this for me!

  • @hotlamon3965
    @hotlamon3965 29 วันที่ผ่านมา

    Are all these tricks possible when using multi-lined f-strings?

    • @Indently
      @Indently  29 วันที่ผ่านมา

      There might be some complications which I’m unaware of, but for the most part yes.

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

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

      @@bronkolie it's a text file. He wrote
      p = .5678
      which should be:
      p = 0.5678

    • @bronkolie
      @bronkolie 27 วันที่ผ่านมา

      @@DrDeuteron sorry, I thought you meant the last zero like in 0.80 vs 0.8

    • @techkid43
      @techkid43 16 ชั่วโมงที่ผ่านมา

      What is the risk from doing this? I've seen it regularly but this is the first I've heard of it being bad

  • @Briggoes
    @Briggoes 21 วันที่ผ่านมา

    What ide is this?

    • @spaniard13
      @spaniard13 9 วันที่ผ่านมา

      He mentioned PyCharm

  • @pointtheblame
    @pointtheblame 29 วันที่ผ่านมา

    Can someone explain why is name and age defined that way with : instead of using "="?

    • @indyplaygames3066
      @indyplaygames3066 29 วันที่ผ่านมา

      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
      @pointtheblame 29 วันที่ผ่านมา

      ​@@indyplaygames3066 so why not just type name = 'indy'? It is obviously a string and the variable is defined ? Is it the same?

    • @fernandezguille
      @fernandezguille 28 วันที่ผ่านมา +2

      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
      @pointtheblame 28 วันที่ผ่านมา

      @@fernandezguille Thank you!

  • @murk1e
    @murk1e 29 วันที่ผ่านมา

    The first example is broken as the name was used as a literal string

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

    • @spaniard13
      @spaniard13 9 วันที่ผ่านมา

      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.

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

    Isn't this a repost?

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

      No, I stated that this was a complete video in the intro.

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

    Me first

  • @omkar_sawant
    @omkar_sawant 29 วันที่ผ่านมา

    You could've just called it F-String Theory

    • @Indently
      @Indently  29 วันที่ผ่านมา

      Thank you for the suggestion

  • @KeithKazamaFlick
    @KeithKazamaFlick 27 วันที่ผ่านมา

    quick maths lol

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

    Why are they called fvck strings?

  • @WilnerSumagingsing
    @WilnerSumagingsing 26 วันที่ผ่านมา

    age = 69

    • @Indently
      @Indently  26 วันที่ผ่านมา

      Its the age of my maturity

  • @daisseur
    @daisseur 29 วันที่ผ่านมา

    Are you french?

  • @markramsell454
    @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?

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

      Did ChatGPT generate this?

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

      Better:
      txt.translate(dict(zip(map(ord, ',_.'), '..,')))