Every F-String Trick In Python Explained

Поділитися
Вставка
  • Опубліковано 6 лют 2025
  • In today's video we're going to be exploring every major f-string feature in Python. It's good to know about these if you love f-strings!
    ▶ Become job-ready with Python:
    www.indently.io
    ▶ Follow me on Instagram:
    / indentlyreels
    00:00 Learning Python made simple00:05 Intro
    00:31 How fstrings work
    02:42 Quick debugging
    04:13 Rounding
    05:42 Big numbers
    08:10 Datetime objects
    09:34 French strings
    11:48 Nested strings
    13:02 Alignment
    16:20 Custom format specifiers
    19:23 Conclusion

КОМЕНТАРІ • 83

  • @U.k358
    @U.k358 2 місяці тому +54

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

  • @johnbennett1465
    @johnbennett1465 2 місяці тому +8

    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 2 місяці тому +15

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

  • @lordstevenson9619
    @lordstevenson9619 2 місяці тому +21

    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 2 місяці тому +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 2 місяці тому +2

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

  • @glg216
    @glg216 2 місяці тому

    Thanks!

  • @marceauh
    @marceauh 2 місяці тому +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  2 місяці тому

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

    • @SantiagoRojo
      @SantiagoRojo 2 місяці тому +2

      Also useful to generate HTML

  • @TsankharXXI
    @TsankharXXI 2 місяці тому

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

  • @sovereignlivingsoul
    @sovereignlivingsoul 2 місяці тому +3

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

  • @elfoyoutube6039
    @elfoyoutube6039 2 місяці тому +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 2 місяці тому

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

    • @elfoyoutube6039
      @elfoyoutube6039 2 місяці тому

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

  • @ROldford
    @ROldford 2 місяці тому

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

  • @TransitPacket
    @TransitPacket 2 місяці тому

    Great tricks! The last one is superb.

  • @rsvdark_main
    @rsvdark_main 2 місяці тому +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"}"}")

  • @elizabethkirby1782
    @elizabethkirby1782 2 місяці тому +1

    Very cool, thanks for all the info

  • @mightyhelper8336
    @mightyhelper8336 Місяць тому

    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

  • @storvattsuisse
    @storvattsuisse 2 місяці тому +1

    This is so useful !

  • @dipeshsamrawat7957
    @dipeshsamrawat7957 2 місяці тому

    Thank you 😊

  • @Dubbidu
    @Dubbidu 2 місяці тому

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

  • @itsMeAsh0304
    @itsMeAsh0304 2 місяці тому

    Great video 🎉🎉

  • @richardferretti8208
    @richardferretti8208 2 місяці тому

    More reasons to love python!!

  • @user-us8th9zn1g
    @user-us8th9zn1g 2 місяці тому +1

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

  • @TRADINGPULSE397
    @TRADINGPULSE397 2 місяці тому

    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 2 місяці тому

    Thank you.

  • @accountdead2305
    @accountdead2305 6 днів тому

    It's adding to my confusion

  • @Ismail_Hassan-77
    @Ismail_Hassan-77 2 місяці тому

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

  • @SantiagoRojo
    @SantiagoRojo 2 місяці тому

    The fr string is pretty useful to write regular expressions

  • @DrDeuteron
    @DrDeuteron 2 місяці тому +20

    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 2 місяці тому +6

      They are pythonic

    • @RandomWolfPrinting
      @RandomWolfPrinting 2 місяці тому

      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 2 місяці тому +6

      How can something built into python not be pythonic

    • @p1geon45
      @p1geon45 Місяць тому +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

  • @uplink-on-yt
    @uplink-on-yt 2 місяці тому

    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.

  • @schwingedeshaehers
    @schwingedeshaehers 2 місяці тому

    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 місяці тому +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 місяці тому +2

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

    • @dragweb7725
      @dragweb7725 2 місяці тому +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 2 місяці тому +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 2 місяці тому

      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 2 місяці тому

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

  • @GoodWill-s8j
    @GoodWill-s8j 2 місяці тому +5

    Every F-String in python is censored.

  • @hotlamon3965
    @hotlamon3965 2 місяці тому

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

    • @Indently
      @Indently  2 місяці тому

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

  • @nuynobi
    @nuynobi 2 місяці тому +2

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

    • @oida10000
      @oida10000 2 місяці тому

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

    • @nuynobi
      @nuynobi 2 місяці тому

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

  • @Dzjur.
    @Dzjur. 2 місяці тому +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.

  • @ivanheffner2587
    @ivanheffner2587 2 місяці тому +1

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

  • @Briggoes
    @Briggoes 2 місяці тому

    What ide is this?

    • @spaniard13
      @spaniard13 Місяць тому

      He mentioned PyCharm

  • @pointtheblame
    @pointtheblame 2 місяці тому

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

    • @indyplaygames3066
      @indyplaygames3066 2 місяці тому

      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 2 місяці тому

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

    • @fernandezguille
      @fernandezguille 2 місяці тому +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 2 місяці тому

      @@fernandezguille Thank you!

  • @DrDeuteron
    @DrDeuteron 2 місяці тому +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 2 місяці тому

      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 2 місяці тому

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

    • @bronkolie
      @bronkolie 2 місяці тому

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

    • @techkid43
      @techkid43 Місяць тому

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

  • @falsemcnuggethope
    @falsemcnuggethope 2 місяці тому

    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 Місяць тому

      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.

  • @murk1e
    @murk1e 2 місяці тому

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

  • @KeithKazamaFlick
    @KeithKazamaFlick 2 місяці тому

    quick maths lol

  • @omkar_sawant
    @omkar_sawant 2 місяці тому

    You could've just called it F-String Theory

    • @Indently
      @Indently  2 місяці тому

      Thank you for the suggestion

  • @ecaltroyer
    @ecaltroyer 2 місяці тому

    Me first

  • @squarerootof2
    @squarerootof2 2 місяці тому +1

    Why are they called fvck strings?

  • @WilnerSumagingsing
    @WilnerSumagingsing 2 місяці тому

    age = 69

    • @Indently
      @Indently  2 місяці тому

      Its the age of my maturity

  • @daisseur
    @daisseur 2 місяці тому

    Are you french?

  • @markramsell454
    @markramsell454 2 місяці тому

    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  2 місяці тому

      Did ChatGPT generate this?

    • @nuynobi
      @nuynobi 2 місяці тому

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