Python Quick Tip: F-Strings - How to Use Them and Advanced String Formatting

Поділитися
Вставка
  • Опубліковано 5 жов 2024

КОМЕНТАРІ • 221

  • @sandeepvk
    @sandeepvk 6 років тому +129

    f string is god send. I am glad I started python in the post 3.6 era

  • @lalligood
    @lalligood 6 років тому +6

    I've been using f-strings for a while but never about the colon formatting "tricks" before this. Nice!

  • @stuthomas3593
    @stuthomas3593 3 роки тому +5

    Another excellent video from Corey Schafer. Easily the best python instructor on UA-cam. I'll be switching to f-string from now on.

  • @theegreatestever2420
    @theegreatestever2420 2 роки тому +3

    Its amazing how short but absolutely clear and excellently explained your videos are. Thank you from South Africa

  • @TheVerucAssault
    @TheVerucAssault 3 роки тому +1

    This is probably the best video I have seen explaining how F strings work. Thanks.

  • @slavoie
    @slavoie 6 років тому +69

    One cool use of f-strings can be to iterate over a dictionary where the keys are strings of integers for some reason (using a JSON dictionary for instance) and get the values out of it directly with integers. No need to add an extra step to convert to strings, just use an f-string!
    Example:
    >>> mydict = {'0': 30, '1': 12, '2': 6, '3': 11, '4': 20} # using strings as keys
    >>> [mydict[f'{i}'] for i in range(4)] # list comprehension to retrieve values in dictionary based on integer
    >>> [30, 12, 6, 11] # list of values retrieved
    Hopefully someone will find that useful... or at least somewhat interesting :).

    • @dominikmoos4814
      @dominikmoos4814 6 років тому +6

      Sébastien Lavoie wouldn‘t it be easier to use str(i) ?

    • @slavoie
      @slavoie 6 років тому +10

      Dominik Moos it is in fact easier to read, but on my machine I can confirm that it is 30% faster to proceed with f-strings using the following test in a terminal:
      python -m timeit -s "mydict = {'0': 30, '1': 12, '2': 6, '3': 11, '4': 20}" "[mydict[str(i)] for i in range(4)]"
      → 200000 loops, best of 5: 1.7 usec per loop
      python -m timeit -s "mydict = {'0': 30, '1': 12, '2': 6, '3': 11, '4': 20}" "[mydict[f'{i}'] for i in range(4)]"
      → 200000 loops, best of 5: 1.18 usec per loop
      As to the reason why this is, I only know f-strings are evaluated at run time but I would be interested to learn more about this! For the time being, I will keep on using f-strings because they are awesome and they save at least two keystrokes every time ;) [str() vs f'']...

    • @dominikmoos4814
      @dominikmoos4814 6 років тому +2

      I agree f-strings are awesome and thanks for the detailed answer!

    • @valentinkhomuteno6825
      @valentinkhomuteno6825 6 років тому +9

      You don't want to go with this solution if you care about perfomance.
      list(mydict.values()) works well and also much faster than hand-written code.
      import time
      large_dict = {f'{i}':i*2 for i in range(10**6)}
      start = time.time()
      values = [large_dict[f'{i}'] for i in range(10**6)]
      end = time.time()
      print(f'done in {end-start}')
      start = time.time()
      values = list(large_dict.values())
      end = time.time()
      print(f'done in {end-start}')
      >> done in 0.48581695556640625
      >> done in 0.027498245239257812

    • @slavoie
      @slavoie 6 років тому

      Валентин Хомутенко thank you! That's very good to know!

  • @doruletu1
    @doruletu1 4 роки тому +1

    Thanks Corey Schafer for f' string quick video explanation!

  • @ajkraftt5480
    @ajkraftt5480 3 роки тому +2

    This was the first time I liked, subscribed and hit the bell icon before being asked. This explains #fstrings on an intuitive level. Well done with the comparisons as well!

  • @kelue3784
    @kelue3784 6 років тому +3

    I am in Shanghai, China. Watching your video is very helpful. I am very interesting about Python.

  • @SACHIN-gd6zy
    @SACHIN-gd6zy 6 років тому +20

    Hey Buddy ur videos are of top quality

  • @lucasflores1
    @lucasflores1 3 роки тому

    your english is clear, your teaching skills are amazing. Thanks!

  • @noobinvestor3180
    @noobinvestor3180 6 років тому +80

    Precise,informative and exact..how do you do this Corey?

    • @eclypsed
      @eclypsed 5 років тому

      AthulRaj Puthalath not even close... a lot of misinformation. .format() can use named placeholders and you can do functions when loading data in.

    • @rajveersingh2056
      @rajveersingh2056 4 роки тому +6

      @@eclypsed you would have to use dot format function use every placeholder as a parameter. I think f string are way more compact than the format function

    • @sharky2606
      @sharky2606 4 роки тому +5

      he reads the documentation, and then makes these videos for people like me that are too lazy to read it and figure it out for themselves

  • @TechReptile
    @TechReptile 4 роки тому

    I have followed your video and get courage to learn python.
    Thanks god I have find you.
    You are really a good guy. Thanks a lot.
    Just carry on.

  • @dsuryas
    @dsuryas 6 років тому +4

    this is similar to template literals in javascript, awesome. Thanks, bro!

  • @WisomofHal
    @WisomofHal 5 років тому +5

    I was introduced to f-strings today in John Zelle's Intro to Computer Science: Python Programming book, which is very good and has taught me the Python I know, so far. I wasn't grasping the concept as quickly as I expected from the book, which has been the only thing I haven't been able to grasp within a few days so I came here to your channel. This makes f-strings look so sexy. Thanks a lot!

  • @WisomofHal
    @WisomofHal 5 років тому +4

    Wow! Came back to this video after letting f'strings mingle in my mind for a few weeks and this is even more golden haha. Really like the calculation exercise you showed uses f'string it's so cool Python allows us to run calculations within the {} Thanks again coach!

  • @srikanth007spl
    @srikanth007spl 6 років тому +2

    Such a delightful feature! Thanks Corey.

  • @denniskamonde6836
    @denniskamonde6836 6 років тому +5

    Thanks Corey Best tutorials Ever

  • @dylancooley9722
    @dylancooley9722 3 роки тому

    You have been a God send with this python playlist! Thank you so much, man.

  • @francistayag
    @francistayag 6 років тому +9

    Thank you, Corey!

  • @akira_asahi
    @akira_asahi 2 роки тому

    Thank you for the video. I am gratuful for your time and contribution. Kind regards, Akira.

  • @andrealopez9556
    @andrealopez9556 3 роки тому

    Thank you so much! You explain it so much better than my teachers.

  • @georgevarelas5073
    @georgevarelas5073 5 років тому +1

    The F-Strings are very useful. Thank you for this high quality video!!!

  • @KakaTu272
    @KakaTu272 3 роки тому +1

    Helpful video , easy and to the point . Thanks mate

  • @sampanicker4725
    @sampanicker4725 4 роки тому +1

    this video was very helpful. Thanks Corey!!

  • @tonglai7499
    @tonglai7499 4 роки тому +8

    Corey Schafer
    in string format video: " String formatting allows us to display exactly the way we would like it"
    Me: Yes I love string formatting!
    Corey Schafer Fstring:"This is not elegant or intuitive"
    Me: bye string formatting

  • @monagulapa3022
    @monagulapa3022 5 років тому +2

    Truly a Pro ! 👏👍

  • @abhisheksharma-ib5vw
    @abhisheksharma-ib5vw 6 років тому

    Nobody can beat you...only You, yourself can beat u... Incredible video

  • @Nathan-f4d
    @Nathan-f4d 10 місяців тому

    sweet swizzle bro. I am beginner python_man and run into some squat.BS and besides skipping through it I use power of UA-cam and notice I gravitate towards your content more of ten than not. Time for burrito and beers brudda

  • @sheepnochy
    @sheepnochy 3 місяці тому

    AMAZING! very clear video

  • @salkdjfasldkfjsdlk
    @salkdjfasldkfjsdlk 6 років тому +5

    Great tutorial as always.

  • @dwaynerobare1153
    @dwaynerobare1153 4 роки тому

    I am a beginner... Really love your videos, the info and your approach to teaching. Please slow down your speaking a bit. Thanks again!

  • @garydunken7934
    @garydunken7934 6 років тому +1

    Well planned tutorial with good examples. Thanks.

  • @WindowzXp
    @WindowzXp 4 роки тому +1

    Saved me a headache. thank you.

  • @NathanY0ung
    @NathanY0ung 6 років тому +1

    already knew most of these except for the datetime one though, thanks :)

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

    very good and clear explanation

  • @parthibanspace
    @parthibanspace 6 років тому +1

    Keep doing this good work Corey! Thanks much.

  • @jingyuchang1885
    @jingyuchang1885 6 років тому +4

    Very informative video! Thanks Corey!

  • @khitesh04
    @khitesh04 6 років тому +1

    Cool will solve some of my formating issues thanks bud

  • @arjunbarakoti4757
    @arjunbarakoti4757 Рік тому +1

    awesome , expecting more and more in python .

  • @ishpeace4886
    @ishpeace4886 4 роки тому

    well-explained and illustrated thanks Corey

  • @luizfernandes7104
    @luizfernandes7104 2 роки тому

    Very helpful and straight forward!

  • @DreamwebMarocasa
    @DreamwebMarocasa 4 роки тому +1

    Thanks for sharing your knowlidge, Great stuff, very useful.

  • @riddhiprajapati9948
    @riddhiprajapati9948 6 років тому +1

    Not only your video, You are amazing too.

  • @AdamSmith-ux5if
    @AdamSmith-ux5if 6 років тому +1

    Love f-strings! Thx for another great video Corey :)

  • @emmanuelchikeluba2360
    @emmanuelchikeluba2360 9 місяців тому

    I understand what you mean by the syntax error that emanates from the wrong use of quotes, however, I used single quotes throughout in mine for the same example and it was perfectly printed on the terminal window without an error message.

  • @RonaldModesitt
    @RonaldModesitt 3 роки тому

    Very helpful. Many thanks.

  • @huntermaverick5114
    @huntermaverick5114 6 років тому +2

    Hi Corey. Great video as always. Can you make more videos about "Real World Example" like the one before? I really like this kind of video and I think they help us understand more of what we can actually do with Python. Thanks

  • @sep69
    @sep69 6 років тому +1

    This sure is a handy feature. Thanks for the video :)

  • @sladefx2955
    @sladefx2955 2 роки тому

    Learned a lot and the video is really well structured aswell. Thank you

  • @itsoktobewhite6377
    @itsoktobewhite6377 Рік тому

    You're killing it dude! 👍

  • @Dr_piFrog
    @Dr_piFrog 4 місяці тому

    Good instructional video, thanks

  • @shubhrajit2117
    @shubhrajit2117 4 роки тому +4

    At 3:55 how do you uncomment the lines without removing the # manually?

    • @francescowang
      @francescowang 3 роки тому +1

      This is what I'm trying to learn as well.

    • @vasudev16180
      @vasudev16180 3 роки тому

      Select multiple lines and then press ctrl + /. By the way, He has been using sublime text 3 editor.

  • @nonalcoho
    @nonalcoho 4 роки тому

    Thank you for your kind tutorial! I learn so much

  • @kennethstephani692
    @kennethstephani692 Рік тому

    Great video, Corey!

  • @JAYS040787
    @JAYS040787 3 роки тому

    Very helpful. Thank you

  • @menghuajiang4314
    @menghuajiang4314 3 роки тому

    Easy to understand even as a newbie.

  • @jonathanwarner2420
    @jonathanwarner2420 6 років тому +2

    Well done, mate. Thx.

  • @jaysanprogramming6818
    @jaysanprogramming6818 6 років тому +3

    Good job! Again... Amazing!

  • @gauravtiwari6392
    @gauravtiwari6392 3 роки тому +2

    Hey Corey, nice video you have there. I had a question though(I don't know whether it concerns with this video), I needed some explanation with the dunder method __format__(). How is it used? Can you provide some examples it would be great. Thanks for this video.

  • @francescowang
    @francescowang 3 роки тому +2

    Legend!!! Thank you. How do you comment and uncomment out using #?

  • @billstrum3203
    @billstrum3203 4 роки тому

    Good job Corey!!

  • @timandrew4515
    @timandrew4515 3 роки тому

    much helpful! thank you!

  • @akbarahmadi8175
    @akbarahmadi8175 4 роки тому +1

    great work

  • @AntiCookieMonster
    @AntiCookieMonster 6 років тому +2

    Just for the record, normal string formatting supports named arguments and key lookups.

  • @davinderbhatia2573
    @davinderbhatia2573 6 років тому +1

    sir your videos are greatest source! please can you make a video on url shortner in python . it would be really helpful. Thanks in advance

  • @thelurkingpanda3605
    @thelurkingpanda3605 5 років тому +1

    You're a godsend

  • @guilhermehx7159
    @guilhermehx7159 6 років тому +2

    Thanks Corey

  • @novicetech1
    @novicetech1 6 років тому +3

    Awesome as always.

  • @notsotacticalninja2409
    @notsotacticalninja2409 5 років тому +3

    Finally some nice explainatory video and step by step explained awesome, p.s. new sub :)

  • @chittipolinaidu1897
    @chittipolinaidu1897 5 років тому +1

    excellent dear

  • @mustinjiles8275
    @mustinjiles8275 Рік тому

    Thank you so much!

  • @SwinginBluesTube
    @SwinginBluesTube 4 роки тому

    your videos are really good. Thank you.

  • @amritdora9960
    @amritdora9960 4 роки тому +1

    good job!!!!

  • @impossibleisnothing9197
    @impossibleisnothing9197 6 років тому +1

    Thank you for the video!

  • @randomguy75
    @randomguy75 6 років тому

    Thanks man. it would great if u made some videos about the new features in Python 3.6 and 3.7.

  • @x-Machina
    @x-Machina 2 роки тому

    This was great 👍🏻

  • @saiganesh4361
    @saiganesh4361 2 роки тому

    Nice info corey

  • @claytonberger
    @claytonberger 6 років тому +1

    You are absolutely awesome!

  • @hanes2
    @hanes2 6 років тому +2

    Do you have tutorials on how to manage localisation in python?
    I only know the Qt way with using their own software

  • @GarimaJain
    @GarimaJain 5 років тому +1

    Thank you!

  • @iamparadox8885
    @iamparadox8885 6 років тому +2

    Sir you are amazing

  • @nazaserh
    @nazaserh 3 роки тому

    Great lesson 👍

  • @susmitamazumder8390
    @susmitamazumder8390 4 роки тому +1

    Hi Corey one of your video I have seen you comment out multiple lines at a single time. How did you do it from the keyboard?
    Sorry I could not remember which video it was though.

  • @otabekisoqov2265
    @otabekisoqov2265 2 роки тому +1

    pretty good however would be better if you provide some extra examples for us to solve

  • @jongcheulkim7284
    @jongcheulkim7284 3 роки тому

    Thank you.

  • @kychemclass5850
    @kychemclass5850 2 роки тому

    Thank you! :)

  • @maudentable
    @maudentable 6 років тому +2

    amazing stuff

  • @dwaynebinns3766
    @dwaynebinns3766 2 роки тому

    Corey 4really love your vids. I am new to.pyyhon and is a self thought person. I am having a hard time adding a line of values with the $ . I want to keep the $ as formatted.

  • @prateeksarangi9187
    @prateeksarangi9187 3 роки тому

    Thanks again

  • @jianwenwu6948
    @jianwenwu6948 6 років тому +1

    Best video ever

  • @jinqimao4781
    @jinqimao4781 5 років тому +1

    Thanks!!!

  • @leenukes7418
    @leenukes7418 6 років тому +2

    Thanks dude ;-)

  • @maxvinella941
    @maxvinella941 6 років тому +1

    Excellent!

  • @MM-oq1lb
    @MM-oq1lb Рік тому

    Can you upload a link to your previous video you mentioned in the beginning of this video?

  • @Hello-iq5ux
    @Hello-iq5ux 3 роки тому

    great video!

  • @walber026
    @walber026 6 років тому +1

    Great one!

  • @YunikMaharjan
    @YunikMaharjan 6 років тому

    please please please do a video on asyncio. Thanks

  • @thattoofunny
    @thattoofunny 6 років тому +2

    You Rock.....

  • @glutzm
    @glutzm 5 років тому +1

    Awesome content!