Python: Show Number as Percentage with Format and F-String

2 minutes read

At the end of ML projects, you often get the accuracy numbers, like R2 score, as a float. What if you want to show them as a percentage on the screen? Let's return to Python fundamentals on concatenating strings and numbers with different options.

Let's imagine you have this number:

r2 = 0.8859687198195745

And your goal is to round it to 4 decimal digits and show it with a percentage, like this:

0.886 (88.60%)

Option 1. Rounding and Float/String Types

The most simple thing to do is just to round and print:

r2 = round(r2, 4)
print(r2)
# Result:
0.886

Great, let's multiply that number by 100 and show it as the percentage on the right, concatenating that as a big string. Right?

print(r2 + " (" + r2 * 100 + "%)")

Wrong. We get an error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

Obviously, Python doesn't allow to concatenate floats and strings. So, if you want to go that route, you need to change all types to str():

print(str(r2) + " (" + str(r2 * 100) + "%)")
# Result:
0.886 (88.6%)

So great, right? Not exactly. We want to force the two-digit percentage result: "88.60%" instead of "88.6%". For that, let's look at alternative Python syntax options for string formatting.


Option 2. Format().

Instead of multiplying by 100, you can pass the initial float value to the format() function:

print(str(r2) + " (" + format(r2, ".2%") + ")")

The format .2% means precisely two decimal digits, so it will show "88.60%" as we want.

Great!

But there's a shorter way.


Option 3. f-string.

There's a Python feature called Formatted String Literals, also known as "f-string".

It allows us to put the string with an f letter in the beginning and use the variable with its formatting directly inside.

This is the syntax:

print(f"{r2} ({r2:.2%})")
# Result:
0.886 (88.60%)

The result will be the same: "88.60%". As you can see, we use {r2:.2%} as a variable, which you could read as {variable:format}.

With that syntax, we don't need to multiply by 100 or change types with str().


No comments or questions yet...