Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'

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

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

  • @sadhlife
    @sadhlife 3 ปีที่แล้ว +903

    What I love f-strings for the most is padding my strings.
    Not only can I do a left align or right align, I can also do a center align, and give it a particular padding character.
    x = 'test'
    f'{x:>10}' → ' test'
    f'{x:*

    • @sadhlife
      @sadhlife 3 ปีที่แล้ว +44

      most of this information comes from pyformat info, great website

    • @sadhlife
      @sadhlife 3 ปีที่แล้ว +5

      @@Imperial_Squid do it :D

    • @stillww
      @stillww 3 ปีที่แล้ว +24

      This should have been in the video it's super useful

    • @snippletrap
      @snippletrap 3 ปีที่แล้ว +3

      Also useful for float formatting

    • @islandcave8738
      @islandcave8738 3 ปีที่แล้ว +2

      Thanks for the tips.

  • @DanielLavedoniodeLima_DLL
    @DanielLavedoniodeLima_DLL 3 ปีที่แล้ว +170

    Also, if you use "%" instead of "f" in the float formatting, it will calculate the percentage and add a "%" at the end.
    For example:
    >>> x = 1/3
    >>> print(f"{x = :.2%}")
    x = 33.33%

  • @Vogel42
    @Vogel42 3 ปีที่แล้ว +391

    i love how fstring can convert between bases really easily:
    >>> a = 42
    >>> f"{a:x}" # hex
    '2a'
    >>> f"{a:X}" # hex (uppercase)
    '2A'
    >>> f"{a:b}" # binary
    '101010'
    >>> f"{a:c}" # ascii
    '*'
    >>> f"{a:o}" # octal
    '52'
    >>> f"{a:010b}" # combined with padding
    '0000101010'

    • @felipevasconcelos6736
      @felipevasconcelos6736 3 ปีที่แล้ว +6

      I wish I could convert to an arbitrary base just as easily. I use seximal a lot, that would certainly help.

    • @definesigint2823
      @definesigint2823 3 ปีที่แล้ว +7

      @@felipevasconcelos6736
      *numpy.base_repr(my_int, base=6)*

    • @felipevasconcelos6736
      @felipevasconcelos6736 3 ปีที่แล้ว +2

      @@definesigint2823, does it work with non-integer bases?

    • @definesigint2823
      @definesigint2823 3 ปีที่แล้ว +4

      @@felipevasconcelos6736 _That_ is an interesting question. Numpy is int 2-36, but *Google* _"Numeral systems with non-integer bases"_ and (Reddit thread) there are several examples in the comments (e.g.):
      ~ Phinary (golden ratio base)
      ~ refs to Knuth's The Art of Computer Programming (negative and irrational bases),
      ~ quater-imaginary (base 2i)
      ~ a link that has Wolfram Alpha do a non-integer base
      ...hope that helps.

    • @felipevasconcelos6736
      @felipevasconcelos6736 3 ปีที่แล้ว +7

      @@definesigint2823 there’s a TH-cam channel called imaginarybinary that showcases a different flavor of base 2i. It’s criminally underrated, last time I checked the whole channel had one comment, and it was mine.

  • @johnathancorgan3994
    @johnathancorgan3994 3 ปีที่แล้ว +43

    I've learned more about f-strings from this video (and comments!) than from the intro documentation. Nice job.

  • @xBaphometHx
    @xBaphometHx 2 ปีที่แล้ว +6

    This is the best Python YT channel for tips and tricks. Glad I found it!
    EDIT: Another thing I learned recently is that you can pass the spaces you want to add between strings inside of the curly brackets.
    Example:
    f"{variable1:{10}} {variable2:{10}} {variable3}"
    That will add a 10 characters limit for variable1 and variable2, so everything looks properly formatted.

    • @Norsilca
      @Norsilca 2 ปีที่แล้ว

      I think by "limit" you mean "minimum". It looks like this is the equivalent of f"{variable1:10} {variable2:10} {variable3}" (without the curly braces).

  • @plagiats
    @plagiats 3 ปีที่แล้ว +41

    4:44 this is useful when you are interfacing with an old system that doesn't support utf-8

    • @mCoding
      @mCoding  3 ปีที่แล้ว +21

      I'm very fortunate that I don't have to do this! Thanks for sharing!

  • @sgian_ime
    @sgian_ime 3 ปีที่แล้ว +81

    Thanks James, this video was really interesting! I’m currently designing a really basic beginner python course for a local high school and your videos are definitely a source of inspiration. Keep up the great work :)

    • @mCoding
      @mCoding  3 ปีที่แล้ว +26

      Awesome! Glad to provide inspiration. Feel free to assign my videos for extra credit 😉

    • @rogervanbommel1086
      @rogervanbommel1086 3 ปีที่แล้ว +5

      @@mCoding $python3 -c ‘print(“same, you are a very good resource”)’
      same, you are a very good resource
      $

  • @JEffinger
    @JEffinger 3 ปีที่แล้ว +14

    f strings are my favorite addition to python since I've started using it.

  • @PythonisLove
    @PythonisLove 3 ปีที่แล้ว +4

    I often use f-strings to tabulate my data...and this tabulation helps when I am trying not to use library for the purpose.
    f'{something:50}{another_one:5}'
    like this!

  • @Bretinator
    @Bretinator 2 ปีที่แล้ว +2

    At around 5:10, you said !s would be the default. I played around a bit and found that this is not quite correct.
    What seems to happen under the hood is that the curly braces around an expression "return" something like format(bangfunc(expression), format_spec), where bangfunc is indeed determined by the char after the bang. But if the bang is absent, bangfunc "defaults to the identity" and NOT to str. format_spec is the plaintext after the colon as a string and defaults to an empty string if the colon is absent.
    As the outer function, format will always call type(bangfunc(expr)).__format__, which only equals type(expr).__format__ IF the bang is absent. Therefore, the format_spec must fit to the type of what bangfunc returns to avoid raising an exception.
    So the reason why {expr} and {expr!s} behave the same in most cases is NOT because they do the same thing:
    for {expr}, bangfunc will be irrelevant because no bang is specified. format will then be called on expr with an empty format_spec. If type(expr) or one of its user-defined bases had defined __format__, it might do arbitrary stuff, but if not, object.__format__(expr, "") will just return str(expr).
    for {expr!s}, str is the bangfunc, so first, str(expr) will be called, which returns a string, lets call it 'stri. THEN format will be called as str.__format__(stri, ""), which defaults to returning stri itself.
    So basically, {expr} and {expr!s} will in general not behave the same as soon as the class of the object returned by the expression uses a __format__ that does not behave like __str__ if the format_spec argument is an empty string.
    I'm aware that these are unrealistic edge cases, but investigating this provided an even deeper understanding for me of how fstrings, format, str and repr are related and implemented.

    • @mCoding
      @mCoding  2 ปีที่แล้ว +2

      Firstly i commend you for this investigation and for taking the time to present your findings. Indeed, my explanation covers only the simple case and excludes discussion of these edge cases which I think are uncommon in real code. Indeed, practically every explanatory video I make could be wrong if the user decided to modify a metaclass, change an element of the builtins module, or use a C extension module because Python is so dynamic. I'll still try to keep things to the most common useful cases on screen, but I'm glad your comment is here for people that want to understand more as you have done. Keep up your inquisitive nature, it will take you far!

    • @Bretinator
      @Bretinator 2 ปีที่แล้ว

      ​@@mCoding Thanks for your kind reply! I really enjoy your videos, it often feels like you manage to see the whole language as just one big picture, with all its countless interactions of which you never lose track or misinterpret since you truly understand what they're built upon. And therefore you know exactly what causes the most headaches for people who only have a shallow understanding of whats going on. I feel like many developers never achieved this or even tried to, because they only see the language as a tool they have to handle "just good enough" and it stays more like countless mosaics loosely glued together, with many links missing, rather than eventually becoming that big picture.
      I also aim for that big picture in everything I try to learn, since only then the process feels satisfying. I guess the inquisitive nature goes hand in hand with that "restriction" :) Also, one of the main reasons why I switched to software development after achieving my physics degree was because "trying out stuff" felt so much faster, which in my opinion is a crucial element for limitless self education.
      Anyway, keep up that great work!

  • @Claxiux
    @Claxiux 3 ปีที่แล้ว +4

    Good vid, would like to add that you can now add thousands separators to numbers you print by doing: print(f'{num:,}') gives you something like 1,000,000

  • @pizzarella985
    @pizzarella985 2 ปีที่แล้ว +1

    3:32 I recommend holding down ctrl when erasing or jumping over a word, it's really useful!

  • @Enthos2
    @Enthos2 2 ปีที่แล้ว

    All these were useful but the equals sign trick at the beginning will save me SO much time
    I immediately thought wow that's amazing for debugging and then you said the same thing right after.
    Thank you!

  • @tristanbroad7915
    @tristanbroad7915 3 ปีที่แล้ว +1

    print(f'
    Start Price {sp:.9f}.
    Current Price {cp:.9f}.
    Change {per:.2f}%.')
    Thanks For the tip this makes my life much better, Also i just found you and you introduced me to dataclasses dataclass making you my new favorite person :D

  • @islandcave8738
    @islandcave8738 3 ปีที่แล้ว +6

    "Good for debugging", you said the same thing I was thinking.

  • @alejandrocarvajal9068
    @alejandrocarvajal9068 3 ปีที่แล้ว +4

    basically, you can use the formating for types in fstring as it was used with .format for previous versions of python, but the advantage is that fstring is a little faster. more information can be found in PEP 498 -- Literal String Interpolation.

  • @ZeroSleap
    @ZeroSleap 3 ปีที่แล้ว +2

    For f-strings,when you use the walrus operator(for whatever reason) you have to put parentheses around the expression for it to work.

  • @peschebichsu
    @peschebichsu 3 ปีที่แล้ว +1

    Wow nice, I just saw the part with {x=} recently in one of your videos and was using it already quite a lot since. Amazing you made a whole video about it

  • @Jaun_
    @Jaun_ 3 ปีที่แล้ว +4

    Great video as always -
    In light of debugging, a great module I’ve been using is “icecream” - high recommend, it has the similar effect to the equals within the f-string.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Cool, thanks for sharing!

  • @WilliamAndrea
    @WilliamAndrea 3 ปีที่แล้ว +2

    ascii() is useful for identifying Unicode "confusables", like the Cyrillic "A".
    >>> 'А' == 'A'
    False
    >>> print(ascii("'А' == 'A'"))
    "'\u0410' == 'A'"

  • @usafa1987
    @usafa1987 3 ปีที่แล้ว +4

    4:44 this is useful when you are using CircuitPython on a microcontroller and driving an LCD display that doesn’t support Unicode

    • @KryptoKiddi
      @KryptoKiddi 3 ปีที่แล้ว +1

      Or when your using user input that will later be called.. it ensures the application will display it properly

  • @andrey2001v
    @andrey2001v 3 ปีที่แล้ว +1

    Thank you for saving a few days of my life that I would've spent on debugging

  • @vasiliynkudryavtsev
    @vasiliynkudryavtsev 3 ปีที่แล้ว +21

    F-string is essentially like F-word, very very cool language feature.

    • @tuck1726
      @tuck1726 3 ปีที่แล้ว +2

      F-string is the closest younger sibling to the g-string

  • @jonragnarsson
    @jonragnarsson 3 ปีที่แล้ว +54

    I can not get over the 'dunder' phrase. All I can think of is The Office.

    • @inigo8740
      @inigo8740 3 ปีที่แล้ว +15

      __Mifflin this is Pam.

    • @Amipotsophspond
      @Amipotsophspond 3 ปีที่แล้ว +4

      yeah, but not in a good way, I don't like it. it seems like jargon. so you have this whole language that can't stand Curly brackets because it looks not like natural language text. Yet then it starts using __init__ instead of the word constructor or Initialize or even just init or con. same with Decorators why @ when it should be dec or "dec nameofdec:" then indented "def thefunctoDec():" or "dec nameofdec(def functodec())", or just "nameofdec(def thefunctoDec():)" these would make it easier to guess out what a Decorators is doing, if you have never seen it. the Decorator looks like a function that is taking in this function I define. it's kind of like a the same as a lambda but bigger. pythonic only cares about readability when you do something complex, but if you talk about getting rid of their jargon syntax sugar to make things more readable they complain about their fingers breaking from extra typing. personalty I find Curly brackets more readable because you are not depending on unseen spaces but I understand they are not to python's style. just saying dunder __ __ has never seemed pythonic and should be replaced. even if it breaks old code because python does not care about breaking old code, it's why python 2 still is a thing.

  • @johnr3936
    @johnr3936 3 ปีที่แล้ว +1

    You rock!! Just changed the way I write code going forward. Man I love this channel, love this info.

  • @georgesanderson918
    @georgesanderson918 3 ปีที่แล้ว +1

    A new mCoding video makes my day!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      And comments like yours make my day!

  • @LostExcalibur
    @LostExcalibur 3 ปีที่แล้ว +10

    Nice video, i learned a lot !

  • @bendiknyheim6936
    @bendiknyheim6936 3 ปีที่แล้ว

    Saw the title, thought "huh, what else could there possibly be". Needless to say I learned some useful things

  • @murirokcs5518
    @murirokcs5518 3 ปีที่แล้ว +2

    f'{val =}' has been very very useful, thank you!!!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Very welcome 😀

  • @xmesones
    @xmesones 3 ปีที่แล้ว

    WOW great video!
    using f-strings
    -------------------------
    age = 21
    def p(val):
    print(f'{val=}')
    p(age)
    --------------------------
    it's possible to show up the argument (age = 21)
    instead, the parameter (val = 21)

  • @DipietroGuido
    @DipietroGuido 3 ปีที่แล้ว +2

    To all of you, the printf function from stdio.h in C has so many of these things too. You would be surprised.

  • @DrorF
    @DrorF 2 ปีที่แล้ว

    This little *f"{var=}"* trick is GOLD!!

  • @Roarshark12
    @Roarshark12 3 ปีที่แล้ว

    Another home run video. I learned about {a=} and __format__(). Very useful, thanks!

  • @entropicflow
    @entropicflow 3 ปีที่แล้ว +1

    Great video as always! Keep it up! Really love the informal feel in this one, a lot like your earlier vids.

  • @lifelikepixel
    @lifelikepixel 3 ปีที่แล้ว +2

    the = sign after the string blew my mind haha
    Thanks!

  • @andrewglick6279
    @andrewglick6279 3 ปีที่แล้ว +38

    I have long loved f-strings, but I never knew how cool they *actually* are. This is great, thanks!
    Any chance you're working on a video about the @overload decorator? I have been very confused about the documentation I've read and knowing your style, I think you could explain it really well!

    • @mCoding
      @mCoding  3 ปีที่แล้ว +8

      I vaguely remember using it in one of my previous videos already... but which one I don't remember. Taking a break on typing related content for a while, python people didn't seem to like it as much.

    • @andrewglick6279
      @andrewglick6279 3 ปีที่แล้ว +2

      ​@@mCoding I vaguely remember something about it too; I'll take a look and see if I can find it.
      I look forward to whatever you work on next, whether its Python or not, you have a tendency to make interesting and educational content!

    • @guyindisguise
      @guyindisguise 3 ปีที่แล้ว +5

      ​@@mCoding typing related content is awesome!
      though to be fair pretty much all your Python content is awesome ;)

    • @homosapienfactory6291
      @homosapienfactory6291 3 ปีที่แล้ว

      th-cam.com/video/yWzMiaqnpkI/w-d-xo.html

    • @homosapienfactory6291
      @homosapienfactory6291 3 ปีที่แล้ว

      Oh nvm you already found it lol

  • @KryptoKiddi
    @KryptoKiddi 3 ปีที่แล้ว +2

    The most useful one for me is ‘!a’ since it will allow me to fine the unicode/short code so the user or I can use it for some functions or features that may not work well with the actual emoji

  • @santasl
    @santasl 3 ปีที่แล้ว

    Interesting. I did not know the additional possibilities of f-string. Thanks for pointing them out and give me a reason to revisit the python f-string page. Maybe there are further interesting ideas for how to improve my programming.

  • @Richard_GIS
    @Richard_GIS 2 ปีที่แล้ว

    Again learnd a lot in 9:09 min, thy -great channel

  • @chonchjohnch
    @chonchjohnch 3 ปีที่แล้ว

    I took a hiatus from python from about 2017 to just recently and lord do I love this things

  • @houssem009
    @houssem009 2 ปีที่แล้ว

    I've been looking for the wrapper thing for days thanks

  • @definesigint2823
    @definesigint2823 3 ปีที่แล้ว +1

    For anyone interested, string interpolation is documented in Python's *PEP-498*
    Here's a question / answer pair to research how fstrings are implemented in Python's source:
    _comments block links so at stackoverflow-dot-com:_ */questions/56635686/how-where-are-fstrings-implemented*

  • @USMColdies
    @USMColdies 3 ปีที่แล้ว

    Everytime I think I have a handle on Python, you burst my bubble with something new

  • @manofqwerty
    @manofqwerty 3 ปีที่แล้ว

    The date formatting is an amazing trick, thanks

  • @BlackHermit
    @BlackHermit 3 ปีที่แล้ว +2

    I knew of the equals sign thing, but the rest was fascinating, thanks!

  • @jewpcabra666
    @jewpcabra666 3 ปีที่แล้ว +1

    This was such a useful and awesome video! I love f-strings so this is super useful to know about. Thanks!

  • @Arrowtake
    @Arrowtake 3 ปีที่แล้ว

    Always learning. First time I saw __format__ used and it makes sense. That's all top of the great f-string tips you had. Thanks!

  • @EsaKarjalainen
    @EsaKarjalainen 3 ปีที่แล้ว +1

    Caveat: {equal_sign=} ignores escape characters such as

    For an example:
    >>> foo
    'stuff
    and
    things'
    >>> print(f"{foo}")
    stuff
    and
    things
    >>> print(f"{foo=}")
    foo='stuff
    and
    things'

    • @mCoding
      @mCoding  3 ปีที่แล้ว +2

      I briefly mention this difference in the video. This is because f'{foo}' uses the str of foo, whereas f'{foo=}' uses the repr of foo. The repr of a str shows escaped characters, so that explains it!

  • @devworks8787
    @devworks8787 ปีที่แล้ว

    Wow. lot of functionalities packed!

  • @DoggoYT
    @DoggoYT 3 ปีที่แล้ว +1

    geez this is actually useful. i would always write __repr__ methods like
    `
    return f"classname('value1={self.value1},'value2'={self.value2})"
    `
    the equals would make this so much easier

    • @patrikjankovics2113
      @patrikjankovics2113 2 ปีที่แล้ว

      Wouldn't that include the `self.` prefix as well though?

  • @rjhornsby
    @rjhornsby 3 ปีที่แล้ว +1

    !a could be super useful trying to debug input - including string values pasted into the code - to figure out that instead of the printable character you expected, it’s some Unicode nonsense like the double dash or fancy double quote character. Generally finding the rogue character means piping the script output to hexdump to see that you have printable ascii values surrounding some weird looking multibyte sequence that doesn’t make sense like x41 x81 xe0 x43 (made up Unicode value, no idea what it is) You can try to string compare that to “ABC” all day long. It might render visually like “ABC” but it’s not ascii ABC. Can see !a as a useful tool here.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      That's a good point, I never thought about that but you're totally right!

  • @cerealport2726
    @cerealport2726 2 ปีที่แล้ว

    I sometimes use f-strings to print results of a process to a file, it's like a cheats way of sending data to a CSV file. I imagine it isn't efficient, but it does the job when you don't have much data, but want to use the output file to check results.

  • @kitgary
    @kitgary 3 ปีที่แล้ว +1

    Really the best feature in Python 3, finally no need to use the format function.

  • @aaronm6675
    @aaronm6675 3 ปีที่แล้ว +1

    Loooove f-strings, love the vid, love the channel 🤠

  • @Veptis
    @Veptis 2 ปีที่แล้ว

    You can not only nest f-strings but also make a whole table with one. Think about `a=f"{{}*3}"` and now is the question of what happens when you have something like `b=[0,2,4]` and then `a.format(*b)`
    Also f-strings can be used outside of print statements. Great for concatenating stuff.

  • @TheTilpo
    @TheTilpo 3 ปีที่แล้ว +2

    Some terminals don't support unicode, I think that's the main use case of `!a`

    • @KryptoKiddi
      @KryptoKiddi 3 ปีที่แล้ว

      Some functions don’t play well with them either so it will help in formatting it for them as well

  • @douglaswolfen7820
    @douglaswolfen7820 ปีที่แล้ว

    I'm gonna find "!s" really useful. I often have integers in my f-strings, and then I want to use the format-modifiers to modify the resulting strings (usually to left-pad the number with spaces or with zeros)
    I've been writing a lot of code like `f"{str(my_num):

  • @chriskorfmann
    @chriskorfmann 2 ปีที่แล้ว

    print(f"{(new_variable := 'whatever you want to assign to new_variable') = }")
    >>> (new_variable := 'whatever you want to assign to new_variable') = 'whatever you want to assign to new_variable'
    print(f"{(now := datetime.now()): %y-%m-%d}")
    >>> 22-05-15
    ^ these actually work. I don't know how or why I would ever use assignment expressions in f-strings but I am now determined to include it _somewhere_ in my code.

  • @Lolwutdesu9000
    @Lolwutdesu9000 3 ปีที่แล้ว +1

    This is really awesome stuff, thanks for sharing it!

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      My pleasure!

  • @NeilMarcellini
    @NeilMarcellini 3 ปีที่แล้ว

    1:02 is exactly what I’ve been looking for!!

  • @SusanAmberBruce
    @SusanAmberBruce 3 ปีที่แล้ว

    Cool! I do like the more informal style thanks

  • @MakinBacon0651
    @MakinBacon0651 2 ปีที่แล้ว

    I was so excided when I learned about f-strings while skimming the notes on the 3.6 release.
    I may or may not have gone into all my code and replaced every format() I could find.

  • @justinfuruness7954
    @justinfuruness7954 3 ปีที่แล้ว +1

    Blown away. How did you come across this stuff?

  • @stevecarter8810
    @stevecarter8810 3 ปีที่แล้ว +2

    So wtf is the encoding of the hex string in !a? Presumably the unicode code point or its internal encoding? Regardless, its useful figuring out what character was actually received when you can't really tell by looking, e.g. Because your console can't display it or it looks similar to another character (X vs Greek chi, etc)

    • @KryptoKiddi
      @KryptoKiddi 3 ปีที่แล้ว

      It’s unicode. I use it for properly displaying emojis

  • @PanduPoluan
    @PanduPoluan 2 ปีที่แล้ว

    Don't forget that the "f" prefix also works with triple-quoted string.

  • @IndellableHatesHandles
    @IndellableHatesHandles 3 ปีที่แล้ว +1

    Every time I think I know Python, I find something I had no clue about.

  • @mydetlef
    @mydetlef 2 ปีที่แล้ว +2

    I'm looking for a way to teach f-strings to use locale. I get from print(f'{1400.0:,.2f}') -> 1,400.00 but I haven't found a way to get something like the German format 1.400,00 through configuration. Of course, I can create the string myself using the locale module, but that means changing all f-strings. Anyone have a suggestion/link?

  • @alperengencoglu5367
    @alperengencoglu5367 3 ปีที่แล้ว +1

    Nice video. Did you forget to talk about nested formatting in the end?

  • @robertbrummayer4908
    @robertbrummayer4908 3 ปีที่แล้ว

    Great job! Your videos are excellent. I enjoy them a lot.

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      Thank you very much!

  • @Han-ve8uh
    @Han-ve8uh 3 ปีที่แล้ว

    I looked at the github and still can't understand the purpose of !s.
    At 5:20, it's mentioned its for when you want to chain formatting operators behind.
    Can anyone show some code examples of how !s makes formatting operators possible that is otherwise impossible without it?

  • @ashishjain518
    @ashishjain518 3 ปีที่แล้ว

    This video is soooo much helpful...
    So glad I found your channel😄😄

  • @eyausoj2065
    @eyausoj2065 2 ปีที่แล้ว

    I fall asleep to these videos 👍 cured my insomnia 👍

  • @itzblinkzy1728
    @itzblinkzy1728 3 ปีที่แล้ว

    Didn't know you could do this with f-strings, good video :)

  • @piotr780
    @piotr780 2 ปีที่แล้ว

    Repr is useful when using print for debugging and logs

  • @CoderrX
    @CoderrX 2 ปีที่แล้ว

    Awesome work
    Loved it!

  • @powder_toy
    @powder_toy 3 ปีที่แล้ว

    i watched this for fun but it actually helped I was writing a programing language in python so it is very text based

  • @MrSteini124
    @MrSteini124 3 ปีที่แล้ว

    Fantastic video, love these fundamentals

  • @whydontiknowthat
    @whydontiknowthat 3 ปีที่แล้ว

    I would have liked to have seen an example using bang s and dunder format at the same time, since you said the point of it was that it does its thing before the format codes. Still, great video!

  • @blzr
    @blzr 3 ปีที่แล้ว

    You can just open doc 2.4.3 and read few paragraphs.
    {x=} format was added in 3.8 only

  • @fadeoffical_
    @fadeoffical_ 3 ปีที่แล้ว

    Even tho I never use python, I still enjoy watching your videos))

  • @indranildas9565
    @indranildas9565 3 ปีที่แล้ว

    f strings is one of my favourite things in python

  • @shashishekhar----
    @shashishekhar---- ปีที่แล้ว

    Thank. You so much for all these

  • @apetrenko_ai
    @apetrenko_ai 2 ปีที่แล้ว

    Amazing! Didn't know half of that!

  • @memespdf
    @memespdf 3 ปีที่แล้ว +1

    Is there a specific reason why you use single quotes when print()'ing but double quotes when setting variables / returning strings?

    • @definesigint2823
      @definesigint2823 3 ปีที่แล้ว +1

      *You can even use docstrings:*
      my_var = """here is a docstring
      it can be on multiple lines
      and retains spaces..."""
      print( f'{my_var}' )

  • @quantumastrologer5599
    @quantumastrologer5599 3 ปีที่แล้ว

    Spooky magic fstrings (great video!)

  • @axxeny
    @axxeny 3 ปีที่แล้ว

    How do you format all floats deep inside a list or a dict, for example, to two decimal places?

  • @SUPERustam
    @SUPERustam 3 ปีที่แล้ว +2

    f’str_value!a’ this case needed for see how string would look like in URL. In URL all non-ASCII symbols will convert to smth like this /U73937489.
    This is my Thought 😀

    • @cmyk8964
      @cmyk8964 3 ปีที่แล้ว

      URL encoding is a lot different. Every illegal character is encoded as UTF-8 and the bytes listed in hex after a %, or in the case of “--xn” encoding, some complex stuff that I can’t really explain.

  • @adamquek1095
    @adamquek1095 3 ปีที่แล้ว

    Cool tips. Thanks!

  • @carsten_
    @carsten_ 3 ปีที่แล้ว

    f'{str_value=}' especially if persist over function scopes, looks like it has some potential for security issues 🤔

  • @_kopiter_
    @_kopiter_ 3 ปีที่แล้ว

    yess, this is exactly what was separating me from being an Ultra programmer!
    a good video btw :)

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Glad you enjoyed it!

  • @pemessh
    @pemessh 3 ปีที่แล้ว

    That = trick would be really handy.

  • @mfaine
    @mfaine 2 ปีที่แล้ว

    What about using this for assignment? Looks like it is actually less work in some cases.

  • @tiagotiagot
    @tiagotiagot 3 ปีที่แล้ว +1

    Isn't this a bit too obfuscated when there would be more clear ways to get the same kind of result by just concatenating strings and functions with the + sign?

    • @mCoding
      @mCoding  3 ปีที่แล้ว +2

      Good question! Well, there is a big performance difference between using + and using f-strings, f-strings are notably faster because every + you use creates a copy of the text. However, even for readability I think most people would prefer f-strings because otherwise you would end up having to manually convert things to strings if they are not already. For instance, print('program done in ' + str(round(t,2)) + 'seconds.') versus print(f'program done in {t:.2f} seconds.'). Of course, this requires programmers to know what the format strings mean, but they are fairly intuitive once you get the hang of it.

  • @Repligon
    @Repligon 3 ปีที่แล้ว

    I still remember how I made a large script with lots of logs, formatted with f-strings. Then I uploaded it on a server and subsequently had to replace all of them with explicit 'format' statements because server was running Ubuntu.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      This seems like more of a version of Python problem and less an ubuntu problem. Well I suppose you may not have had access to upgrade the Python so I guess that's fair. Always good to keep in mind what software your system has.

    • @Repligon
      @Repligon 3 ปีที่แล้ว

      @@mCoding I think, it took them almost a year to finally upgrade to python 3.6. But yes, it is a version problem that I encounter pretty frequently with Debian based distros.

  • @bassenji5565
    @bassenji5565 3 ปีที่แล้ว +1

    Thanks a lot for the very interesting video! I was wondering, what would be the use case of writing a __format__ method instead of a __repr__ one within a custom class?

    • @mCoding
      @mCoding  3 ปีที่แล้ว +1

      You're welcome! Consider the case of a Date object. You would want both a format and repr. The repr might print out something like Date(year=2021, month=9, day=17), but with a format method you could allow users to print it as either 2021/17/09 or 9/17/2021 or or Sept. 9, 2021, or whatever they want. Format method allows the developer to give the user the freedom to print out the class in a variety of different ways.

  • @Omena0
    @Omena0 ปีที่แล้ว

    Why didint you do all of the formatting stuff like alignment and making sure all of ur print statements print the same length even with diffrent variables
    Eg f"{var:

  • @vvvv-lo8or
    @vvvv-lo8or 3 ปีที่แล้ว +430

    I feel like Python is your Girlfriend and you know all the tiny little secrets about it😅

    • @axelnils
      @axelnils 3 ปีที่แล้ว +17

      ”it”

    • @VoltageLP
      @VoltageLP 3 ปีที่แล้ว +32

      that's creepy

    • @Xiph1980
      @Xiph1980 3 ปีที่แล้ว +31

      You think you'll ever get to know all the tiny little secrets of a girlfriend? That's cute... 🤣
      ...
      Also, a bit creepy.

    • @obed818
      @obed818 2 ปีที่แล้ว

      @@Xiph1980 haha yeah

    • @ananttiwari1337
      @ananttiwari1337 2 ปีที่แล้ว +2

      uhh... her? 😂

  • @chriskeo392
    @chriskeo392 2 ปีที่แล้ว

    for the .2f
    I don't need Decimal module anymore?!???

  • @ahasibrifat7568
    @ahasibrifat7568 2 ปีที่แล้ว

    should use f'sting in SQL queries? any security issue?

  • @saitaro
    @saitaro 3 ปีที่แล้ว

    Thanks, mate, I subbed.

    • @mCoding
      @mCoding  3 ปีที่แล้ว

      Welcome!