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 :).
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'']...
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
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!
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!
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
@@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
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!
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
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.
@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']}" ?
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'"
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
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.
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.
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.
f string is god send. I am glad I started python in the post 3.6 era
Scammers
@@kamal3777 ?
@@farajshaikh5100 i have no fucking idea
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 :).
Sébastien Lavoie wouldn‘t it be easier to use str(i) ?
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'']...
I agree f-strings are awesome and thanks for the detailed answer!
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
Валентин Хомутенко thank you! That's very good to know!
I've been using f-strings for a while but never about the colon formatting "tricks" before this. Nice!
Another excellent video from Corey Schafer. Easily the best python instructor on UA-cam. I'll be switching to f-string from now on.
Its amazing how short but absolutely clear and excellently explained your videos are. Thank you from South Africa
This is probably the best video I have seen explaining how F strings work. Thanks.
your english is clear, your teaching skills are amazing. Thanks!
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!
I am in Shanghai, China. Watching your video is very helpful. I am very interesting about Python.
Thanks Corey Schafer for f' string quick video explanation!
Hey Buddy ur videos are of top quality
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.
At 3:55 how do you uncomment the lines without removing the # manually?
This is what I'm trying to learn as well.
Select multiple lines and then press ctrl + /. By the way, He has been using sublime text 3 editor.
Nobody can beat you...only You, yourself can beat u... Incredible video
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!
Thank you for the video. I am gratuful for your time and contribution. Kind regards, Akira.
Thanks Corey Best tutorials Ever
You have been a God send with this python playlist! Thank you so much, man.
this is similar to template literals in javascript, awesome. Thanks, bro!
Helpful video , easy and to the point . Thanks mate
You're killing it dude! 👍
Such a delightful feature! Thanks Corey.
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
this video was very helpful. Thanks Corey!!
Precise,informative and exact..how do you do this Corey?
AthulRaj Puthalath not even close... a lot of misinformation. .format() can use named placeholders and you can do functions when loading data in.
@@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
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
I am a beginner... Really love your videos, the info and your approach to teaching. Please slow down your speaking a bit. Thanks again!
awesome , expecting more and more in python .
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!
Thank you so much! You explain it so much better than my teachers.
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
Thank you, Corey!
The F-Strings are very useful. Thank you for this high quality video!!!
AMAZING! very clear video
Great video, Corey!
Great tutorial as always.
Love f-strings! Thx for another great video Corey :)
very good and clear explanation
Very informative video! Thanks Corey!
Saved me a headache. thank you.
Not only your video, You are amazing too.
well-explained and illustrated thanks Corey
Very helpful and straight forward!
Good job Corey!!
Good instructional video, thanks
Keep doing this good work Corey! Thanks much.
Well planned tutorial with good examples. Thanks.
Thanks for sharing your knowlidge, Great stuff, very useful.
Very helpful. Many thanks.
This sure is a handy feature. Thanks for the video :)
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.
Thank you for your kind tutorial! I learn so much
Learned a lot and the video is really well structured aswell. Thank you
Well done, mate. Thx.
Awesome as always.
Very helpful. Thank you
@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']}"
?
Easy to understand even as a newbie.
your videos are really good. Thank you.
Good job! Again... Amazing!
already knew most of these except for the datetime one though, thanks :)
Cool will solve some of my formating issues thanks bud
much helpful! thank you!
This was great 👍🏻
Great lesson 👍
Nice info corey
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'"
great work
sir ur a legend big up
Legend!!! Thank you. How do you comment and uncomment out using #?
Just for the record, normal string formatting supports named arguments and key lookups.
Thank you for the video!
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
Thanks Corey
You are absolutely awesome!
Finally some nice explainatory video and step by step explained awesome, p.s. new sub :)
You're a godsend
excellent dear
Awesome content!
holy crap, you are awesome
subbed!
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?
good job!!!!
Great one!
Thank you so much!
Best video ever
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
great video!
Excellent!
Sir you are amazing
Why I am getting "TypeError: 'module' object is not callable" for 11:00 example with datetime?
import datetime
birthday = datetime.datetime(1990,6,18)
print(f"Corey's birthday is on :{birthday: %B %d %Y}")
TRY THIS BROTHER !!
Thanks man. it would great if u made some videos about the new features in Python 3.6 and 3.7.
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.
amazing stuff
Thanks dude ;-)
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.
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')}"
Yeah, it's never a good idea to run unsanitized user input, whether that's in an f-string, format method, or database query.
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.
Thank you!
Can you upload a link to your previous video you mentioned in the beginning of this video?
Thank you! :)
Thanks again
Where can I find the documentation for formatting? Thanks a lot!