13 Python f-string formatting tips

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so pythonet strings are cool but they're kind of old news well basically python F strings allow you to insert the result of pretty much any python expression into a string let's take a look let's say we have a name look as Viana and you want to say hello to the name so how do you do that well with up strings it's simple before the first opening quote add an F and then anything inside curly braces gets evaluated and inserted into that string so all we have to do is type name here and then when we evaluate that we print successfully hello Lucas Gianna or whatever the variable name was but as I said this is old news and this truly is just the basics it is only when we look into the details that things start getting more interesting so here's step number one know where to find the documentation so the python documentation is wide and deep and rightfully so the language has many features and a comprehensive standard Library so you can get a little bit daunting to try to find a specific chapter so let's browse to dot dot python.org we'll look for f strings and that is baked into the language so let's go to language reference and then we look under literals chapter 2 the 4.3 formatted string literals [Music] take your time to understand this the syntax may look a little bit dense at first but it's not that hard and then when we read through this and try to digest and try to understand what the format spec would realize that this page doesn't really tell you exactly what a format spec is but it links us to the python format specifier mini language and here we find another one of the syntax definitions so you can understand that there is really no way around learning these things well I have carefully read all of those specifications and that leads us to tip number two different data types have different options this is basically a condensed aggregation of many of the things from the documentation that we just looked at and then I realized that of all these options we will never use all of them at once if my expression is a string I only have these options available if my expression is an integer on the other hand I only have these options available and if it's a float I only have these options available don't worry about all of that for now the coming tips will go over the best combinations for those options some of these options though can be used for any data types and my favorite option of all leads us to tip number three abuse the debugging help if you have an equal sign right after the expression python will not only insert the result of it as usual it will also insert the expression itself inside the string so you don't have to do it manually how great is that so let's go back to our grading example here let's add an equal sign after the name now we see the result is printed and before it we see the expression followed by an equal sign and the expression gets printed out unmodified really for any expression let's take a look so if you add something after here so as we saw before if we convert this to uppercase the entire expression gets printed out tiny equal sign in the end and boom you get awesome results so the next tip is more like a full program I went all in so creating tables with f strings is a breeze let's take a look so this is done using these four Fields fill alignment with and possibly a maximum width when we are dealing with strings specifically so back to our trusted notebook here let's say that we have a list of items for sale each item has a name say genes and a price one hundred dollars or whatever bomber jacket and let's change the price 200 last item let's say shoes whatever and costs eight dollars let's start by simply printing them out nothing fancy so four item in items print let's already start with our F strings and let's insert a replacement field an item name and item price and this one also needs to be surrounded by curly braces perfect print this out we see that it's nothing fantastic now let's pimp this up to improve this let's use the width format specifier we simply add a colon and a number for the width on both Fields here colon and number and now we see the things align much better but I'm fill in there a little bit too far apart so let's reduce this to 15 and see where we end and now let's copy this line and paste it over here at the top and we're creating a header here so we're going to say that this is the name and this is the price things are starting to look much better now let's play with the alignment option for the alignment we have three options a left square bracket to align left numbers align right by default we can align right so let's try here with the right square bracket the names jumped to the right or we can align center with a carrot now the names are align Center let's give this aligned left for now I don't use this often but you may specify any of your character by adding the character to the left of the of the alignment option so let's insert the dollar sign here and see that it looks terrible so to the left of the alignment everything up to the width gets filled up with this dollar signs yeah it looks terrible so let's remove it but there it is like for all that I know this is a table and all that we had to do was to add a couple of characters after our expressions and this start to demonstrate the power of these things and they go much further Beyond let's say for example that you have pretty long name here bomber jacket is a very long name okay well now you see that our alignment was lost so what do we do that leads us to our next tip use the max width field for Strings the maximum width option is quite hidden in the documentation and it comes almost as an afterthought in the text the field is actually called Precision in the documentation and is commonly used for floating Point numbers so here's how we fix this overflow problem that we're having we use the max width to truncate the name by adding a DOT followed by a number that specifies the maximum width of this field and voila we see here that the bomber jacket is a long long name gets truncated to the maximum of 15 characters most of the times when tabulating values it is a good idea to use this maximum width for Strings so the next step takes things to the next level we can parameterize the formatting options let's take a look so just to give an example here let's say that we want to parametrize the width so the width is variable so everything we see 15 we will replace by the variable that we're going to create called with less equal to 15. but let's create it as a string already so python doesn't need to do any extra work and then in here inside our replacement field we have another replacement field with the width inside and everything everywhere we see this we're going to go around and replace and I'll even go ahead and say that we're always going to want the maximum width which would be the same as the width so now we're free to change this width to whatever we want say 50. and everything follows along quite nicely and if we want to parametrize also the alignment we would be able to do that just as easily we just need to create a variable called alignment and say that this is the alignment that we want and if we want to change the alignment to Center for example that's all that we need to do but for now we're going to keep things unparametrized so let's undo this all this example only uses positive numbers but if we had negative numbers the numbers wouldn't quite align because the sign would be in the way so that leads us to tip number seven align numbers correctly take into consideration their signs so let's take a look so let's say that some of these numbers are negative and for clarity let's start with integer so we're going to have to change the price by something that is an integer quantity here so let's say Quantity so everywhere we see price we change to quantity and then this quantity is 17 this one is say 20 and this one let's use a negative quantity well I don't know what a negative quantity really means maybe you oversold a product or maybe you have some pre-orders or whatever that means let's look how it prints out and by the way you also need to change this one to quantity let's see and also let's get rid of this long name here so we have a nice separation of the field so now we see that the things don't look terrible but they don't look perfect so here since we're dealing with integers we have these options for formatting integers we can see that by preceding the width field with a plus character we tell python to show the plus sign even for positive numbers so let's try this out if we have the plus sign before the width we're telling python to print the plus sign even for positive numbers and if you ask me this aligns already a little bit better but there is an even better option that is to replace this plus sign by a blank space so python allocates this little space for the positive numbers just so the positive numbers align with the negative numbers that's neat what is not really neat though is that this space here having a white space really means something in python is not very pythonic so that's the kind of stuff that makes me shed a tear so I would have this ugly white space with a mini in the middle of my stuff tip number seven write a line and pad with zeros there might be a situation where you want to align your numbers to the right and then pad them with zeros to the left and that is not always very obvious and I'm gonna show you why there are two ways really for filling up numbers with zeros up to the width and one of them is wrong so let's try out some dumb ideas here let's start by showing the plus sign for all the numbers so Things become very clear so the film character really comes before the alignment character here we can already see that this was a terrible idea we certainly don't have 17 billion trillion items for sale so padding numbers with zeros to the right is always a terrible idea so let's do the better thing not correct yet and align it to the left zeros here don't mean anything but then we got this plus sign trapped in between so how do we fix that this little problem here is the reason why we have this zero option here which means pad with zeros but be smart about the signs so instead of doing this let's proceed the width field by a zero so we have this different option so python knows that we want a mathematical correctness and it still looks strange so what's going on the solution comes to our next tip use the equal alignment option for numbers exclusively the equal alignment operator is the default for numbers and unless you want that left alignment Aesthetics the equal alignment operator will always do the right thing for you so let's check it out so all that we have to do is to replace this alignment the right angle bracket by the equal sign which also means a line right and voila now python knows that we want mathematical correctness when it comes to padding our numbers with zeros so we know that all these zeros to the left don't mean anything and the plus sign is not trapped inside there anymore and this ladies and gentlemen is how you align right and pad with zeros I have no idea why you would want to do that I have never needed that but in case you need there you have it and our next tip I promise is going to be a lot more useful I use this all the time and it's going to help you be kind to your customers around the world use Locale specific formatting let's check it out to exemplify this I'm gonna need some larger quantities into the thousands so let's take these and add three zeros to each one and let's also remove this right alignment nonsense and the right alignment since it's the default we're gonna keep it like that we're gonna remove the plus sign that is terrible syntax but quite pretty actually let's do a left alignment here just because just to get keep things a little bit more tight to the left and now let's say that we want to improve readability of these large numbers here by adding a thousand separator one way according to the documentation is to add a coma after the width so that is going to add the coma as the Thousand separator another option is to have an underline and that's going to have an underline as a thousand separator that's nice but depending on the country of our customers the standard thousand separator character might be different so how do we deal with this what we can do instead is to use the N type specifier let's try it out so instead of using this we use a type instead and the type is n nothing happened but that is because my local settings aren't really helping let's fix that by faking that we are somewhere else so how do we do that so up top here I am gonna import Locale and I'm gonna say Locale dot set locale locale.lc numeric and let's set it to America for example e n u s that's the code for American lookup so python by itself without my interference uh already chose the correct thousand separator for that country so people in the US are going to look at these numbers and they're going to know that that comma means the Thousand separator let's pretend we are in Germany for example so to do that we just need to type D E dot d for Deutschland and now we see that they don't really use any thousand separator okay let's try Sweden instead SVS e oh in Sweden we have uh space as a thousand separator let's try PT BR for Brazil and there they use a DOT as a thousand separator so we see that we can't really choose the Thousand separator on behalf of our customers because different cultures have different standards on what they really see in the numbers and Americans seeing this dot here they might think that this is a fractional number whereas a Brazilian person might look at this number and really think it's uh 17 000. so this can avoid a lot of confusion and the cool thing about that is that you don't need to worry about where customer is in the world let their local settings do the job of choosing the Thousand separator and everything else how cool is that and talking about the type specifier there are many types available and that is the next tip easy base conversion so let's start fresh here let's say that we have a number n and so the number is 127 825 and now let's print we know we're dealing with F string n and let's see that that's spreading correctly yes that is printing our number back to us and now we can start exploring the different options that we have for converting the base of this number so looking at the documentation for integers we have these types available B for binary X for hexadecimal o for octo and kind of weirdly we have the C to print out our Unicode character that corresponds to that point there are better ways to do that in Python a little bit more pythonic I don't know why they did it but no it's there let's write these options out now let's type our colon to tell python that everything that comes after the colon is the format specifier remember now let's skip everything and go straight to the last option is the type and let's put a B for type and that's telling python that hey print this in binary format for me and there you go python does its job and this is the binary representation of the number 127 825 the hexadecimal representation as easy as replace that by an X and the octal representation is this strange number and the last but not least if we print the Unicode character that is represented by this huge number we get this Emoji the pitch Emoji code point is really 127 825 and the next step is to improve the readability of these things use hash and underline for base conversions so from the documentation we have that this hash means alternate representation and the underline is the separator that we've talked about before so all that we have to do let's go back to our binary representation so we have those binary numbers and before the B we add the hash for binary representation and we have this 0b added before the number and that greatly improves readability that tells everyone reading this number that this is a binary number and not the number one trillion one hundred and eleven thousand that makes it clear what kind of Base we're talking about and to really knock this out of the park in between the two we use the separator let's use the underlying separator and now python is grouping those in groups of four and that makes the number a thousand times more readable now we see that oh here's my first byte oh here's my second python so my recommendation here really is use the hash and underline uh for the separator for when you're doing base conversions because it makes things much much easier to read that's all you need and that's really simple and at the same time is elegant and sophisticated and somewhat important sometimes said that the ultimate sophistication is Simplicity and this is what we're getting to here and do you know what is even more sophisticated than that it's to know what's going on under the hood so you have the full power at your hand to alter and shape things as you want so let's take a look at that the next tip is know what's under the hood I have saved the best for last so congratulations if you made this far formatting like that is so easy that it makes it seem like magic but the Machinery behind is quite simple so let's check it out okay so for example we have an F string and we have an object D being inserted into that string with a certain format specification whatever those values are for now we're going to get into that this is equivalent to calling the format built-in function passing in the D object and the format spec as arguments and this according to the documentation will result in a call to the dunder format method on the type of that object with the object itself and the format spec as arguments this is in the documentation and this would make you believe that this format method should be a static method because you're passing the object itself here but this is not quite true and I don't really know why the documentation says things like that but what this hints to us is that it's really simple to create objects that have our own format specification so well let's do that let's create our object with our own format specification so first of all we need to create a class I'm very uncreative by now so I'm going to call this class hello and we're gonna construct it with an init method which always receives self and let's say they receives a message very very creative right now and then we give this property called message which is the message that is passed in and how to make this work with the format built in we need to Define format Dunder method here and this we're not going to Define this as a static method we're going to Define as a normal method that simply receives the format specification here and then we can do something with this object so let's create some format specification for our object so let's do something simple let's say that if we pass in the letter U as a format specification we convert things to uppercase and if we pass in the letter L we convert things to lowercase let's try it out so if formats back equals to U we return self.message Dot Upper otherwise if the format spec equals to L then we return self. message dot lower yes last but not least if we don't recognize the formats back we don't do anything special self Dot message without any Transformations so there it is this is our class so now let's use the class and let's use our format specification so let's instantiate it so Hello type with a message hello there we're seeing here that my creativity is through the roof and now all that we have to do is to print the object inside an F string and we're going to interpolate that object here and we're going to put a colon for our format specifier and we're gonna give here either the letter U or the letter L we're going to see if the message gets converted to uppercase and there you go it gets converted to uppercase and we've passed the L here everything goes in lowercase the first H here is in lowercase and now we have our own formatting for our object that we can quickly select using the format specifier after the colon here how cool is that and with that cherry on the cake we conclude this video and hopefully you have taken your python app string knowledge to the next level this is my first real YouTube video ever so leave some love in the comments like subscribe and let me know what you thought about the video and all those things that YouTubers are supposed to say in the other videos but right now my focus is not to grow this channel but to learn how to make high quality content so if you have constructive feedback I would really appreciate that and that's it for me today and see you in the next video
Info
Channel: Lucas Viana
Views: 10,358
Rating: undefined out of 5
Keywords: python, f-strings, string, formatting, programming, table format, format
Id: 44DMWikS0Ds
Channel Id: undefined
Length: 26min 4sec (1564 seconds)
Published: Sat Aug 12 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.