5 Useful F-String Tricks In Python

259,621
0
Published 2024-02-11

All Comments (21)
  • @andymitchell2146
    I've been using python for about 10 years, and f strings extensively, but never knew that last tip! Game changer!
  • @Zenivo
    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.
  • @_Loki__Odinson_
    This is the first time I have seen someone specify datatype for variables in python, and I honestly loved it. Great tips btw.
  • @BohumirZamecnik
    Very nice. Another useful is formatting float as percent: f"{foo:.2%}".
  • @TheJaguar1983
    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.
  • @rolandsz8831
    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"
  • @TheMcSebi
    Great video! Didn't know about the datetime and debug print ones. Definitely going to use them in the future, though.
  • @jaa928
    Thank you for the instructive tips!
  • @quekki3666
    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
  • @bashar9200
    This is amazing!! thank you for this tutorial!!
  • @SergioYT2052
    "Simple y bello como un anillo", como diría Neruda; pero además, muy funcional. ¡Muchas gracias!
  • @mattshu
    F strings are soo chef kiss
  • @timegor844
    Wow, so many simple things I didn't about... Thank you