13 Python f-string formatting tips

Поделиться
HTML-код
  • Опубликовано: 27 июл 2024
  • Get the cheat sheet: lucasviana.podia.com/f-string...
    In this video we go deep into Python f-strings and the slightly hidden "formatting mini-language", which is an absolute gem that I use all the time. The string formatting mini-language is jam packed with goodies but it is hard to use it effectively just from reading the documentation. In this video I'll lay out some 13 of my best tips for using this wonderful, yet terse, Python feature.
    Timecodes
    0:00 - Intro
    0:56 - Formatting mini-language documentation
    2:13 - Formatting different data types
    2:58 - Print debugging messages conveniently
    3:51 - Creating tables with f-strings
    6:57 - Max width: truncating strings
    7:50 - Parametrize f-string formatting
    9:22 - Aligning numbers is not that simple
    11:25 - Padding with zeros the right way
    12:57 - Align numbers to the right, the right way
    14:08 - Respect the users' locale
    17:35 - Easy base conversion
    19:25 - Print the base and use separators for readability
    21:21 - The _format_ method and format() builtin
  • НаукаНаука

Комментарии • 95

  • @JWalker2004
    @JWalker2004 4 месяца назад +6

    I would not have guessed this was your first RUclips video. I am college student trying to learn more about Python and programming in general. I really appreciated how you broke down the documentation to be more understandable. I hope you make more Python videos in the future.

  • @madhuhadas15370
    @madhuhadas15370 8 месяцев назад +12

    this is the type of video that I am looking for. I like explanations with examples instead of just writing away like crazy. thank you very much

    • @ViianaCodes
      @ViianaCodes  5 месяцев назад +2

      I often read your comment for motivation to keep going with this channel. Thanks for the kind words :)

  • @GPrime808
    @GPrime808 4 месяца назад +3

    Great video! You had structure, clarity, and timely precision. Amazing job for a first video, I would have thought you've been doing this for years

  • @hansdietrich1496
    @hansdietrich1496 8 месяцев назад +5

    Well done. I do python for a long time, but never went that deep into f-strings.

  • @ellisfrancisfarros3935
    @ellisfrancisfarros3935 4 месяца назад +4

    Absolutely underrated channel!

    • @ViianaCodes
      @ViianaCodes  4 месяца назад +1

      Really appreciate it! Thanks! 🙏 Now let's tell RUclips's algorithm to show my videos to more people 😅

  • @darrenlefcoe
    @darrenlefcoe 2 месяца назад +1

    a nice little reminder...

  • @moonilyas
    @moonilyas 4 месяца назад +1

    Yeah, great knowledge you shared for Python f String functionality to us on RUclips, Thanks!🤩

    • @moonilyas
      @moonilyas 4 месяца назад

      More Python information expected, and A huge request you can share step by step tutorials for Python Beginners, Intermediate and then Advance programing, because delivering approach is Great for learner's, hope request will be appreciated 😁

  • @thedudegotfourviews
    @thedudegotfourviews 4 месяца назад +4

    Learned a lot from this video. Thank you. I hope to learn more in the future.

  • @JohnMatthew1
    @JohnMatthew1 6 месяцев назад +1

    Love deep dives on simple stuff like this, thank you!

  • @exenzi
    @exenzi 11 месяцев назад +3

    Thank you! These visuals (2:18) are really helpfull.

    • @ViianaCodes
      @ViianaCodes  11 месяцев назад +1

      Glad you like them!

  • @TurloughCowman
    @TurloughCowman 11 месяцев назад +2

    Brilliant! I'll be using some of these. Thanks.

  • @mauricemichael4146
    @mauricemichael4146 5 месяцев назад +3

    Wonderful lesson and amazing explanation. Thank you

  • @simonwillover4175
    @simonwillover4175 7 месяцев назад +3

    Thank you so much for the well organized video. This really shows a lot of the more nuanced and useful ways to use the format specifier. Of course, you didn't cover things like float formatting, but you DID show a lot of related concepts.

    • @simonwillover4175
      @simonwillover4175 6 месяцев назад +1

      Plus you hinted at how float formatting works in the beginning of the video, so it's no big deal.

  • @ttrev007
    @ttrev007 8 месяцев назад +3

    excellent job. i cannot think of anything to critique. ... never suggest that i look at Python's documentation, it is word soup to me. lol. seriously you did a great job explaining the notation. I plan on referring back to this video when in need to use f string notation to make it really stick.

  • @rmb706
    @rmb706 3 месяца назад +1

    This was super helpful. I read the documentation, but theres a lot of things in it that were not clear to me before watching these videos. I often find myself completely unable to learn new python stuff by reading the documentation. It just doesn't make sense without examples. I don't understand why examples aren't more commonly packaged with documentation.

    • @ViianaCodes
      @ViianaCodes  3 месяца назад

      Yeah, some parts of the docs take hours to wrap my head around, especially the syntax definition parts. Keep at it though! Reading the docs is the way :)

  • @capability-snob
    @capability-snob 8 месяцев назад

    Very nice, I can finally let go of %!
    Did you know: builtins use a slightly different algorithm for finding methods to prevent some nasty recursion bugs. It is called Special Method Invocation in the docs. It searches the type's MRO and invokes __get__ on any descriptor found, but does not search the instance variables or call __getattr__ as the default implementation of __getattribute__ does. __getattribute__ implements the "." operator that you are used to. Hence, "type(d).__format__". It's not exactly the same, but it does get across the point that instance variables don't enter into the lookup.

  • @mkriskt
    @mkriskt 11 месяцев назад +2

    Beautiful - looking forward for more videos. 👍

  • @Momotaroization
    @Momotaroization 5 месяцев назад +1

    This is good pedagogy.

  • @Pongo8844
    @Pongo8844 11 месяцев назад +3

    Thank you for the clear enunciation and pacing of your explanation. This makes a big difference in understanding.

    • @ViianaCodes
      @ViianaCodes  11 месяцев назад

      Oh thanks! It really makes me glad to hear that

  • @academianobresilva_10
    @academianobresilva_10 11 месяцев назад +2

    Clear like clean water!

  • @rokuroenmado3822
    @rokuroenmado3822 8 месяцев назад +1

    daaaamn! this is HIGH QUALITY indeed! a man who really know his stuffs. One of the best teachers in Python here in YT (the best or 2nd of the best).

  • @ColinTimmins
    @ColinTimmins 4 месяца назад +1

    Wow, this was really good! I’m learning to code so I can build my own solutions to solve problems that I have that will include GPT assistants. I’m dyslexic and have ADHD that’s inhibit my learning. Your in-depth explanation and how you presented everything was beautiful. Subbed for anything else you create in the future. =]

    • @ViianaCodes
      @ViianaCodes  4 месяца назад

      Wow, what a beautiful comment! I'll post a print of it on my Instagram (@senhor_lucas mostly private stuff) because I really need to share this. Thank you very much! And see you soon in the next video!

  • @adityagolpalliwar1408
    @adityagolpalliwar1408 7 месяцев назад +1

    Will definitely use these tricks to update my ugly logging statements.

    • @ViianaCodes
      @ViianaCodes  7 месяцев назад +1

      Oh no! Don't do that ;) For logging one should not use f-strings to avoid overly eager interpolation. That is one of the edge cases where we should stick to % strings. Should I make a video about that?

    • @adityagolpalliwar1408
      @adityagolpalliwar1408 4 месяца назад

      Yeah, that would be very helpful!
      @@ViianaCodes

  • @1superloki
    @1superloki 8 месяцев назад +1

    You're my new iSource for python Very informative

  • @DennisGentry
    @DennisGentry 4 месяца назад +1

    Hi, this is a nice video. I have one small suggestion: Even when you're just writing an example, if you add a docstring to the class or function, it'll be clearer what the bit of code is trying to do.

  • @AlexIstrate_Ro
    @AlexIstrate_Ro 11 месяцев назад +5

    In Romania the "correct" decimal separator is '.' and the thousands separator, when used, is ','. But, when using a computer, everybody expects the reverse (en_US). So, in practice, if you try to format numbers correctly, you end up creating even more confusion.

    • @ViianaCodes
      @ViianaCodes  11 месяцев назад +2

      Locale settings... Always creating confusion.
      Btw, in Romanian locale 'ro_RO' the grouping character is the dot '.' and the decimal separator is the comma ','. That's probably what you meant?
      The final decision whether to use locale specific or fixed separators depends on the intended audience, right?
      And we are all scarred from MS Excel. It somehow gets it all wrong!

    • @HenrikMyrhaug
      @HenrikMyrhaug 4 месяца назад

      In my opinion, apostrophes should be used to group powers of 1000, that way it is completely unambiguous when you see:
      123'456,789
      compared to the ambiguous nature of either:
      123,456.789 or
      123.456,789

  • @boomershare9707
    @boomershare9707 8 месяцев назад +1

    This was fun to watch, especially towards the end. Thank you.

  • @mehdiyahiacherif2326
    @mehdiyahiacherif2326 7 месяцев назад

    i rarely comment on a video, but man you did some research here, great video

    • @simonwillover4175
      @simonwillover4175 7 месяцев назад

      Research? Oh, c'mon! It doesn't take very much research to learn about this topic. But I am extremely glad he made such a well organized video for us!

  • @Dougie373
    @Dougie373 7 месяцев назад +2

    This is super helpful, I'm returning to learning python right now and nice clear explanations like this are so nice to have 😁

  • @gabrielschultz6872
    @gabrielschultz6872 4 месяца назад +2

    Gostei de como você explica as coisas e muito legal você ter lembrado de incluir a documentação, algo que muita gente esquece em tutoriais e coisas do tipo.

    • @ViianaCodes
      @ViianaCodes  4 месяца назад +1

      Valeu Gabriel! Obrigado!🙏

  • @shawnpereira3042
    @shawnpereira3042 8 месяцев назад +2

    This is a very well made and informative video. Hope to see more. 😊

  • @bobruddy
    @bobruddy 6 месяцев назад +1

    learned a ton. great video and it was really engaging. Thanks for the detail! I'll be honest and I did watch it sped up, but maybe I was already familiar with 30% of f-strings and wanted to extract the new bits I didn't know. So not suggesting you should shorten it, but want to let you know so you could understand how your new audience is using the videos.

    • @ViianaCodes
      @ViianaCodes  6 месяцев назад

      I'll try to create a "shorts" with the summed up content. Thanks for the kind and honest feedback, really appreciate.

  • @WAYK5634
    @WAYK5634 8 месяцев назад +1

    Bundle of thanks

  • @DarcyCrumb
    @DarcyCrumb 4 месяца назад +1

    Great work, thank you!

  • @olearydj
    @olearydj 7 месяцев назад +1

    Nicely done. I suggest you make a pdf of the overall and type specific formats available via a link in the description.

    • @ViianaCodes
      @ViianaCodes  7 месяцев назад +1

      lucas-viana.com/posts/python-f-strings/

    • @olearydj
      @olearydj 7 месяцев назад

      awesome, thank you!@@ViianaCodes

  • @permadidluve
    @permadidluve 8 месяцев назад +1

    It's indeed a high quality video. I am eager waiting for your next video. Keep up the good work and explanation

  • @manikanta5696
    @manikanta5696 8 месяцев назад

    Great video! Its feel like untouched corner topic in python which i have seen and also explained very well.
    Keep doing this things lucas

  • @mkwise5996
    @mkwise5996 4 месяца назад +1

    Great video

  • @LucasRibeiro
    @LucasRibeiro 8 месяцев назад +1

    Awesome content!

  • @kekkaigenkei
    @kekkaigenkei 4 месяца назад +1

    Great video. Can you make more videos on design pattern, best practice in python coding, or OOP for data science?
    My main weakness is i also test every variable first so i can make a proper function out of it LOL

  • @famaral42
    @famaral42 10 месяцев назад

    Excellent content, never seened before. Pode criar mais! 🎉

  • @shaurryabaheti
    @shaurryabaheti 6 месяцев назад +1

    Awesome video.... I am late to the party here but I am glad to know about stuff I didn't know.... like type conversion and the __format__ method.... real niceee Thanks man :)

    • @ViianaCodes
      @ViianaCodes  5 месяцев назад

      I was reading this comment again and realized that RUclips is rendering the `__format__` as itallic. I wonder what other shenanigans it is up to! Let's test.
      - Bullet points starting with a dash?
      - *Single asterisk*
      - **Double asterisk**
      - _single underline_
      - __double underline__
      - `back ticks`
      ```
      tripple back ticks
      ```

    • @ViianaCodes
      @ViianaCodes  5 месяцев назад

      Ok, so surrounding things with a single asterisk render it as *bold* and surrounding it with a single underline renders it as _italic_. Cool! But can we \_escape\_ it somehow?

    • @ViianaCodes
      @ViianaCodes  5 месяцев назад

      This is a really motivating reply for my tiny channel! Thanks :)

    • @shaurryabaheti
      @shaurryabaheti 5 месяцев назад

      @@ViianaCodes
      So I read your comment and then I read mine again, yeah, RUclips made me have a syntax error lol. But like a good dev, I searched about this and how to fix my "bug" and if more such "bugs" exist.
      I found that 3 such "bugs" exist,
      1. *bold* (using asterisks)
      2. _italics_ (using underscores)
      3. -strike through- (using hyphens)
      These "bugs" can be chained as per liking:
      1. *_bold and italics_*
      2. _-italics and strike through-_
      3. *-bold and strike trhough-*
      4. *_-all three-_*
      These "bugs" only happen if you "accidentally" add a whitespace or new_line character before (logical AND operator) after the enclosed string. So to prevent them from happening, we can add some punctuation after the enclosure to escape these "bugs".
      1. *timid*.
      2. _why are italics called italics_?
      3. -who uses strike through? Honestly a code block presenter would have been so much better-!
      4. _*When you chain them, the last one will be escaped if you don't have a white_space before (logical OR operator) after it*_.
      RUclips should definitely have a WSYIWYG text editor in-built, it feels so weird typing this and sending so I can see the output. Classic programmer curse, can't see the output before running it lol.

    • @shaurryabaheti
      @shaurryabaheti 5 месяцев назад

      @@ViianaCodes
      I really appreciate videos that teach me something new, I can then incorporate these into my previous code to get more functionality, like I can make a __format_._() method (escaping the previous "bug") inside a data-class to get the data out however I wish, for example let's say I made a class about imaginary numbers, I can surely create a method to display them in the Cartesian form but I can also create the __format_._() method so that I can easily output it. It works fantastic.
      I am an intermediate python programmer but I always look for videos about concepts I already knew about as there is always new information to have, maybe it also went through and update that I missed. It's an adventure and I am all for it.
      So you don't gotta thank me, just keep these good videos coming. I don't value channels through their newness, I value them through their content, and this was one of the most useful video about f-strings I have seen yet so *_cheers_* !!

  • @keenoogodlike
    @keenoogodlike 4 месяца назад +2

    please use dark reader, I can't stand the light :) nice tips btw

    • @ViianaCodes
      @ViianaCodes  4 месяца назад

      Oh, hadn't thought about that. In my day-to-day work I actually use dark reader otherwise my eyes fall off when switching from the editor to the browser!

  • @user-px9bi1uh5t
    @user-px9bi1uh5t 10 месяцев назад +1

    I really liked the video, keep up the good work. Ps. Your very handsome!

  • @gurupartapkhalsa6565
    @gurupartapkhalsa6565 8 месяцев назад +1

    unicode is a type because it has special characteristics. you'd format it into hexadecimal (typically) but unicode is not fixed width. a unicode character can be anywhere from 1 to 4 bytes, and some of the bits are used to encode the length of the character. as a user, you are not expecting to read the encoding bytes, but the actual integer->alphabet mapping value without the character-header.

    • @ViianaCodes
      @ViianaCodes  7 месяцев назад +1

      Nice that you mention that! I have a plan for an entire video about encodings, going into UTF-8, UTF-16 and how they relate to Unicode and ASCII. Will also try to squeeze in some info about Latin-1 and other things that should be buried :) As Bill Gates would say, •¡

  • @17crescent
    @17crescent 11 месяцев назад +1

    excellent video

  • @academianobresilva_10
    @academianobresilva_10 11 месяцев назад

    Muito bom!

  • @RealEstate3D
    @RealEstate3D 10 месяцев назад +1

    For de_DE the thousand separator is “.”!!

    • @ViianaCodes
      @ViianaCodes  10 месяцев назад

      I was confused when nothing showed up... I wonder what happened. Will dig a little here.

  • @joanpere8863
    @joanpere8863 6 месяцев назад

    What about aligning numbers at the decimal separator?

    • @ViianaCodes
      @ViianaCodes  6 месяцев назад

      What kind of floating point output are we aiming for? With scientific notation or fixed point it would be a breeze, but the generic formatting it would be really hard!

  • @lisichkoslav
    @lisichkoslav 11 месяцев назад

    13:50 how about format binary numbers. Like i want to show 00000001 instead of 1 for example

    • @ViianaCodes
      @ViianaCodes  11 месяцев назад +1

      Thanks for your comment! Usually we only print only the necessary digits. For example the decimal number 6 would be printed as 0b110. But if you are printing, for example, a full byte, then you would want 0b0000_0110, which would look pretty neat. In this case I would use this f'{6:#011_b}'. Makes sense?
      f'{6:#011_b}' -> 0b0000_0110
      f'{6:#010b}' -> 0b00000110
      f'{6:09_b}' -> 0000_0110
      f'{6:08b}' -> 00000110

  • @ArjunSharmatechy
    @ArjunSharmatechy 5 месяцев назад +1

    I wish you have have completed it with float :P

    • @ViianaCodes
      @ViianaCodes  5 месяцев назад +1

      I knooow! It was the plan but I ended up with 4 hours of footage and decided to drop the float part. The thing is that floats are much harder in comparison so I promise I'll do floats in a future video. There are some mind blowing things details that I am eager to share.

    • @ArjunSharmatechy
      @ArjunSharmatechy 5 месяцев назад

      @@ViianaCodes will wait for it and kudos to you for such quality content . Will love to see more crisp videos from your channel .

  • @colinmaharaj
    @colinmaharaj 6 месяцев назад +1

    I'll stick with C

  • @kenhaley4
    @kenhaley4 5 месяцев назад +1

    Nit: ">" and '

  • @IAMTHESWORDtheLAMBHASDIED
    @IAMTHESWORDtheLAMBHASDIED 10 месяцев назад +1

    dude... I needed to get to sleep like hours ago, well, 15 minutes ago is still an hour below my goal, lmfao... anyways, FUCKING LOVE F'STRINGS THANK YOU! LOL O.o