Loading video player…

Dealing With Percentages in F-Strings

00:00 Let’s have a look at another format specifier, and let’s use an example used in the previous lesson. One third is, and within the braces, one divided by three.

00:09 Now, instead of choosing how many digits you want after the decimal point, maybe you want to treat this as a percentage. So one third is 33.33%, and there is a form specifier for this.

00:22 So once again, we have the colon, and then you can put in the percentage sign. And that indicates to your f-string that you want to treat this number as a percentage.

00:31 So instead of 0.333, you end up with 33.33%. But once again, you don’t want all of those threes, perhaps you only want a couple of them, 33.33% for example.

00:44 So in this case, you can put the .2, but instead of the f, which indicates you want to treat as a float, here we have the percentage sign, and in this case, one third is 33.33%.

00:59 And let’s look at the other example you had in the previous lesson. The tax was 0.2 and you might want to say the tax rate is, and then within curly brackets, you’re going to put the tax.

01:14 However, it’s unlikely you want to show it this way. Normally when it’s a tax rate, you want to say 20%. So once again, you can put the colon and put the percentage sign, and it says the tax rate is 20%, yes, but with lots of zeros, we don’t want that.

01:29 So you can make it clear that you want zero digits after the decimal point. So the format specifier after the colon is .0%, and the tax rate is 20%.

01:44 And we only need a short summary for a short lesson. So you can use the percentage symbol as a format specifier, and this indicates that the value should be treated as a percentage.

01:55 And you can also add a dot and an integer as you did with the f when you had floats. In this case, the format specifier in this case, for example, is .2%.

02:07 So treat the value as a percentage, but only use two digits after the decimal point.

Become a Member to join the conversation.