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

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

КОМЕНТАРІ • 224

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

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

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

    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!

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

    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 3 роки тому +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.

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

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

  • @ajkraftt5480
    @ajkraftt5480 4 роки тому +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.

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

    Thanks Corey Schafer for f' string quick video explanation!

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

    Hey Buddy ur videos are of top quality

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

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

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

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

  • @WisdomofHal
    @WisdomofHal 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!

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

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

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

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

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

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

    Helpful video , easy and to the point . Thanks mate

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

    You're killing it dude! 👍

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

    Such a delightful feature! 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

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

    this video was very helpful. Thanks Corey!!

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

    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 5 років тому +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

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

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

    awesome , expecting more and more in python .

  • @WisdomofHal
    @WisdomofHal 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!

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

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

  • @Nathan-f4d
    @Nathan-f4d Рік тому

    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

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

    Thank you, Corey!

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

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

  • @sheepnochy
    @sheepnochy 6 місяців тому

    AMAZING! very clear video

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

    Great video, Corey!

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

    Great tutorial as always.

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

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

  • @brefeye
    @brefeye 5 місяців тому

    very good and clear explanation

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

    Very informative video! Thanks Corey!

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

    Saved me a headache. thank you.

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

    Not only your video, You are amazing too.

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

    well-explained and illustrated thanks Corey

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

    Very helpful and straight forward!

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

    Good job Corey!!

  • @Dr_piFrog
    @Dr_piFrog 6 місяців тому

    Good instructional video, thanks

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

    Keep doing this good work Corey! Thanks much.

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

    Well planned tutorial with good examples. Thanks.

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

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

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

    Very helpful. Many thanks.

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

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

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

    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.

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

    Thank you for your kind tutorial! I learn so much

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

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

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

    Well done, mate. Thx.

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

    Awesome as always.

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

    Very helpful. Thank you

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

    @6:20
    What is the difference between:
    sentence = f'sentence with placeholder {person["name"]} {person["age"]}'
    sentence = f"sentence with placeholder {person['name']} {person['age']}"
    ?

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

    Easy to understand even as a newbie.

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

    your videos are really good. Thank you.

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

    Good job! Again... Amazing!

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

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

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

    Cool will solve some of my formating issues thanks bud

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

    much helpful! thank you!

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

    This was great 👍🏻

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

    Great lesson 👍

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

    Nice info corey

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

    hey.. ive been using f strings the same way until today.. it says f is not defined for some reason.. k = f"user = '****', passwd = '*********' , host = 'localhost', database = '{dbname}',charset = 'utf8'"

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

    great work

  • @takumifujiwara5737
    @takumifujiwara5737 18 днів тому

    sir ur a legend big up

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

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

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

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

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

    Thank you for the video!

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

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

    Thanks Corey

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

    You are absolutely awesome!

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

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

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

    You're a godsend

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

    excellent dear

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

    Awesome content!

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

    holy crap, you are awesome
    subbed!

  • @JoshuaMartinez-hu5bg
    @JoshuaMartinez-hu5bg 6 років тому +1

    Hey Corey, Around 8:10 when I include padding, I get a ValueError: Unknown format code '\x20' for object of type int. What am I missing?

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

    good job!!!!

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

    Great one!

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

    Thank you so much!

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

    Best video ever

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

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

    great video!

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

    Excellent!

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

    Sir you are amazing

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

    Why I am getting "TypeError: 'module' object is not callable" for 11:00 example with datetime?

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

      import datetime
      birthday = datetime.datetime(1990,6,18)
      print(f"Corey's birthday is on :{birthday: %B %d %Y}")
      TRY THIS BROTHER !!

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

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

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

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

    amazing stuff

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

    Thanks dude ;-)

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

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

    notice expression in F-string is evaluated by the server side, you may get ur sever pwned by someone typing in f"{__import__('os').system('id')}"

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

      Yeah, it's never a good idea to run unsanitized user input, whether that's in an f-string, format method, or database query.

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

      True, but that's not the point of me mentioning this. F-string simply enlarges the attack surface of a python-web app, user input is given a chance to be evaluated by server. Say there is a traditional input mirror interface that merely reflects user input by its design. You would be only talking about some html/entity encoding to avoid security problems, mostly XSS(malicious JS, client side). For the F-string style, hackers are given a chance to test against filtering/sanitizing rules, among which succeeded attempts may result in an SSTI(malicious Py, server side). Additionally, things like f"{a_server_side_secret_token_with_a_long_variable_name_that_hackers_can_read_using_this_method}" cannot be dealt with a general filtering rule as it appears to be a normal string without any 'attack vector' in it. The extra price of sanitizing user input with F-string support is high enough to persuade most developers to stick with the old-school string formatting.

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

    Thank you!

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

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

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

    Thank you! :)

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

    Thanks again

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

    Where can I find the documentation for formatting? Thanks a lot!