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

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

Corey Schafer 12.07.2018 241 068 просмотров 7 708 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we will be learning how to use f-strings to format strings. F-strings are new to Python3.6+ and are extremely useful once you learn how to use them. Viewers have likely seen me use f-strings in previous videos so this video will go into detail exactly how to use them so that everyone can follow along confidently. Let's get started... ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (11 сегментов)

Intro

hey there how's it going everybody now this is going to be a quick video where I show you a feature that you've likely seen me use and a lot of my videos so far and that is F string so f strings are a new way to format strings in Python 3. 6 and above and I prefer using them over any other formatting methods so if you're not using Python 3. 6 or higher then you'll need to install that in order to follow along with this video okay so let's take a couple of examples and see why I prefer using these so first of all I have two variables here at the top so I have first name and last name so let's say that I wanted to print a sentence that says my name is and then include the first name and last name in that string now the way you've probably been familiar with doing this is with the format method and this is how I used to do it too as well so we have our curly braces here as placeholders and then we're using our format method to feel in the placeholders with these values so the first name is going to put get put in the first placeholder here and the last name is going to get put in the second place holder here now if any of this is unfamiliar to you then I do have an older video where I go in-depth on how to use the format method that goes over a lot of these same examples that I'm going to use in this video with F strings so if you're curious then you can watch that first okay so this should work how I have it right now with this format method so if I save this and run it then you can see that we did get our sentence with our values that we wanted but right now this is not extremely elegant or intuitive so for example if we have a lot of placeholders then we kind of have to go back and forth to see what placeholders match up with what values so I'd have to go back and forth between the format method here and the placeholder to see where what is going to get filled in where but now let's see what this looks like using an F string so I'm going to comment out what we have here and I'm going to uncomment out the section here and I'll bring this up one

Using FStrings

so far here I have a sentence that has our two placeholders and I've removed the format method now instead we're simply going to use an F string and to specify that we want this to be an F string then we just put an F in front of the string here to tell Python that this is going to be an F string a formatted string and now instead of using the format method we can simply add our variables directly into our placeholders so within the curly braces here I'm going to say first name and within the second one here I'm going to say last name so if I save this and run it then you can see that we get the same result and that this works but also look at how much more intuitive this looks we no longer have to go back and forth between our placeholders and the format method to see what will be added where we can just look at this directly and see that our string will be equal to my name is and then our first name and then followed by space and then our last name now another cool thing is that we can actually run functions or methods directly within the EPS string so let's say that we wanted our first and last name to be capitalized so to do that we could simply come in here and say first name dot upper and also say last if I save that and run it that you can see then our output it says my name is and then it capitalized our first name and last name so I personally think that that's extremely simple and a lot easier to read than if these were in a format method okay so let's take a look at how we would print out some dictionary values using an F string so I'm going to remove all of this and uncomment out this section here so I have a dictionary

Using Format Methods

here and the dictionary just has a key of name with a value of gin and a key of age with a value of 23 and now I have another sentence here where we have a couple of placeholders and I'm using a format method for now and to the first placeholder we're passing in this person and accessing that name key which should be gin and the second value here we are putting the person and accessing that h key which should be 23 so this sentence should say my name is Jen and I am 23 years old so this is how we would do this with the format method so if I save this and run it then you can see that works fine but now let's see how we do this with an F string so I'm going to comment out that and uncomment out our second part here so we have our string

FStrings

with our placeholders and we also have our F at the beginning to specify that this is an F string now there is one thing that we need to watch out for here now since we are now going to access the keys directly within the string we now have to figure out what to do with the quotes we're using to access that key so let me show you what I mean so if I try to just put this in directly into our placeholder like we did before so I'll say person and access our name and then also person and access the age then our

Double Quotes

single quotes that we're using here to access our key to our dictionary is terminating our string early because we opened our string with a single quote as well so if I run this then it should give me a syntax error and it does it says invalid syntax so to avoid this if you're using single quotes inside of your F string then simply use double quotes to open and close your string then the single quotes will no longer conflict with those and I do this with normal strings as well I'd rather change the quotes than look at a bunch of escape sequences and stuff like that so let me change the opening and closing quotes so if I come in here I'll just open this with a double quote and I will close that now our single quotes are no longer affecting the opening or closing of our string so now if I save this and run it then you can see that works fine okay so now let me show you a few other things that we can do before ending this video so let me uncomment out this line here so like I said we can run functions

Calculations

and methods from directly within the F string but we can also do calculations so in this example I and simply go into our placeholder so our string says four times eleven is equal to and I can simply go in our placeholder and say four times eleven and then I can save that and run it and we can see that within our F string it did that calculation so it says four times eleven is equal to forty four now we can also do some more advanced formatting and our F strings as well so in this next example let me uncomment out this in this example I am looping

Pads

through a range of values of one through ten and I am just printing those out through each loop so I'm printing out the value of n each time we go through the loop so if I save this and run it then we can see that our result is the value is 1 by use 2 and so on but let's say that I wanted each of these values to be 0 padded by a certain amount so sometimes it can be important to 0 pad values when adding them to a database or to expect a certain length or anything like that so to do this we can go up into our F string here and just put a colon after our value to specify that we're going to do some additional formatting and now if we wanted to 0 pad by 2 digits then we can simply say 0 to specify 0 padding and then 2 for 2 digits so if I save that and run it then now we can see in our loop here that all of our values have a leading 0 except for the 10 because it's already two digits so if we wanted to 0 pad by 3 or 4 digits or whatever then you can simply change this 2 to whatever you'd like so if I change that to a 4 save it and run it you can see that now we are Z 0 padded with four digits total okay so now let's move on to floating point values so let me get rid of that and oncome and uncomment this section here

Precision

okay so here I have pi written out to a certain number of values and in our string we are simply printing that out so we have an F string here that says pi is equal to and then just printing out pi so if I save that and run it then we can see that works but what if that is a longer floating point number than what we want to print so let's say that two four digits than to do this we can put a colon after our value here and the place holder like we did before to specify that we're going to do some extra formatting and now we to specify that we want to only print up to four digits then we can say point here a dot to specify a floating point and then I'll say four four digits and then an F for a floating point value so I'll save that and run it and you can see that now we have a precision of four that we're printing out this value and we can see that it also rounded this up correctly so it's not just chopping that value off and again if you'd like to change the precision then you can simply change that forward to any value that you'd like so if I do five save that and run it then you can see that now it's five digit precision there okay so lastly let's take a quick look at formatting and printing dates so I'll get rid of that there and come down here and uncomment out this section and I'll separate out the import statement there

Date Time

now this is probably the kind of formatting that I use most often because the way that we want to display dates can vary so much okay so I have created a date time here that is a fake birthday of January 1st 1990 and we can see that we're currently just passing this date time directly into our placeholder in our F string and printing that out so let's see what that looks like by default so if I save this and run it then we can see that it says jen has a birthday on 1991 one and then the minutes and seconds there so we can see

DateTime Formatting

that that's not the best-looking output now we can read it but it would be nice if we could change this to whatever we'd like so let's say that I wanted to this to literally output you know Jen has a birthday on January 1st 1990 now to do this we're gonna have to know the date/time formatting codes and I never remember these I'm constantly needing to look them up but if we go to our site here this is just the Python documentation here in section eight point one point eight towards it's basically towards the bottom of the date-time documentation and this will give you the codes for whatever output you want so for example we can see that the percent sign uppercase B here is the code for the entire month spelled out and it gives some examples here and the lowercase B here is an abbreviated month so remember for our output I wanted it to say January 1st 1990 so what we're gonna want is this uppercase B to spell out January and then it looks like this lowercase D is the day and then for the year we want this capital Y to do a four-digit year this lowercase Y is just a two-digit year without the century so we're going to go with the uppercase Y so let's go back to our example and now let's fill in these values to format our string how we like so just like we've seen before I'm going to add a colon after our value to specify that we want to do some additional formatting here and now we can just type in how we want this to look using those codes that we solve from the documentation so I'm gonna say % b2 have the month first and then a space and then % D to give the day and then I'm going to do a comma after the day and then to do the year that's going to be % uppercase Y so now if I save this and run it then we can see that it says Jin has a birthday on January 1st comma 1990 so we can see

Conclusion

that we got the formatting that we were hoping for and that worked well ok so I think that is going to do it for this video hopefully now you have a good idea for how you can use f strings and if you see me using it in future videos then nothing will throw you off but if you do have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that these dis ways to simply like the video and give it a thumbs up and also a huge help to share these videos with anyone who you think would find them useful and you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник