- How To Print A Percentage Value In Python?
- What is Percentage Value?
- How to Convert the 4/5 in Percentage Value?
- How to Print a Percentage Value in Python?
- Example 1: Print Percentage Value Using Format Function in Python
- Example 2: Print Percentage Value Using Format Function in Python (With Precision)
- Example 3: Print Percentage Value Using F-string in Python
- Example 4: Print Percentage Value Using F-string in Python (With Precision)
- Example 5: Print Percentage Value Using Formula
- Summary
- References
- Python String Interpolation with the Percent (%) Operator
- The % Operator
- Free eBook: Git Essentials
- Aligning the Output
- Conclusion
How To Print A Percentage Value In Python?
Different fields like Machine learning, Data science, and Deep learning make use of ‘data’ to build different models. We perform different tasks on the ‘data’; some numbers/results are in the form of ‘Percentage values‘. Let’s understand how to print a percentage value in Python.
The domains like Machine learning and Data science build models using Python language. Sometimes, these models perform mathematical calculations, and results are printed in the form of percentage values. For example, The accuracy of every model is printed in the form of percentages, like 99.7%, or 98.5%. These percentage values are very important in this model for analysis.
In some models, we need to use mathematical formulas to evaluate the results. For example, very basic operations like 1.0/3.0 = 0.333, can be converted into the percentage value i.e. 33%. These operations may be a small part of the big calculations. Let’s see the percentage values in detail.
What is Percentage Value?
The percentage value is a result of dividing two numbers and multiplying the result by 100. The percentage value is always represented with the ‘%’ suffix. Let’s see some simple examples to understand the percentage values.
How to Convert the 4/5 in Percentage Value?
The result of 4/5 is 0.8. After multiplication, the value becomes 80%. The final result is ‘80%’. In this way, we can calculate the percentage values.
It is very simple when we perform these calculations manually or using a calculator. There are many methods in Python language to print percentage values. Let’s see the examples.
How to Print a Percentage Value in Python?
There are different methods in Python to print the percentage value. All methods are easy and understandable. Let’s see the examples one by one.
Example 1: Print Percentage Value Using Format Function in Python
The format function in Python is used to replace something in the string. The format function is used to replace every data type like integer, float, string, character, etc. So, it becomes easy when we use the format method to print the percentage value in Python.
Number = 0.75 Percentage_value = "".format(Number) print(Percentage_value)
In example 1, The Number holds the float value ‘0.75’ which is used in the .format() function. The second line of code consists of syntax “”, which is used to print the % sign and percentage calculation without any precision. This value will be replaced by the ‘Number’ and printed in the next line.
The output of example 1 is 75% which is correct!
Example 2: Print Percentage Value Using Format Function in Python (With Precision)
Format function can be used to print the percentage values with precision. Let’s implement the example to see the result.
In this code, “” denotes the precision of two numbers in the output.
The output of example 2 is 88.89% which is correct!
Example 3: Print Percentage Value Using F-string in Python
The f-string in Python works similarly as a format function. The f-string is used with curly braces, and ‘f’ is used as a prefix. This f-string will replace the things from the curly braces with the given string. Here, we’ll replace the original value with the percentage value.
Number = 0.53 Percentage_value = f"" print(Percentage_value)
In this example 3, we use f-string instead of the format function but the working is the same. The Number contains the value and the ‘:.0%‘ syntax will help to convert an original value into a percentage value. Let’s see the result.
Example 4: Print Percentage Value Using F-string in Python (With Precision)
Here, let’s print the percentage value using f-string in Python.
Here, in this example 4, the percentage value is printed with the 2 precision places, ‘.2%’ denotes the 2-precision points.
The output of example 4 is ‘53.73%’ which is correct!
Example 5: Print Percentage Value Using Formula
There is simple technique/ formula to print the percentage value in Python, which is very simple but for knowledge, we can implement it.
Here, in this example 5, the formula to get the percentage value is directly used. The simple string is printed with a ‘%’ sign. After comparing all the examples, this one is the easiest technique to print percentage values in Python.
Summary
This article covers the topic of how to print percentage values in detail. Some basic topics like, what is percentage value? how to get the percentage value? printing the percentage value using different functions like format and f-string, examples with precision is also given. Hope you will enjoy this article.
References
Do read the official documentation on format and f-string for details.
Python String Interpolation with the Percent (%) Operator
There are a number of different ways to format strings in Python, one of which is done using the % operator, which is known as the string formatting (or interpolation) operator. In this article we’ll show you how to use this operator to construct strings with a template string and variables containing your data.
The % Operator
This way of working with text has been shipped with Python since the beginning, and it’s also known as C-style formatting, as it originates from the C programming language. Another description for it is simple positional formatting.
The % operator tells the Python interpreter to format a string using a given set of variables, enclosed in a tuple, following the operator. A very simple example of this is as follows:
'%s is smaller than %s' % ('one', 'two')
The Python interpreter substitutes the first occurrence of %s in the string by the given string «one», and the second %s by the string «two». These %s strings are actually placeholders in our «template» string, and they indicate that strings will be placed there.
As a first example, below we demonstrate using the Python REPL how to print a string value and a float value:
>>> print("Mr. %s, the total is %.2f." % ("Jekyll", 15.53)) 'Mr. Jekyll, the total is 15.33.'
Just like the %s is a placeholder for strings, %f is a placeholder for floating point numbers. The «.2» before the f is what indicates how many digits we want displayed after the decimal point.
These are just two simple examples of what is possible, and a lot more placeholder types are supported. Here is the full list of placeholder types in more detail:
%c
This placeholder represents a single character.
>>> print("The character after %c is %c." % ("B", "C")) The character after B is C.
Providing more than a single character as the variable here will raise an exception.
%s
This placeholder uses string conversion via str() prior to formatting. So any value that can be converted to a string via str() can be used here.
>>> place = "New York" >>> print("Welcome to %s!" % place) Welcome to New York!
Here we only have a single element to be used in our string formatting, and thus we’re not required to enclose the element in a tuple like the previous examples.
%i and %d
These placholders represent a signed decimal integer.
>>> year = 2019 >>> print("%i will be a perfect year." % year) 2019 will be a perfect year.
Since this placeholder expects a decimal, it will be converted to one if a floating point value is provided instead.
%u
This placeholder represents an unsigned decimal integer.
%o
This placeholder represents an octal integer.
>>> number = 15 >>> print("%i in octal is %o" % (number, number)) 15 in octal is 17
%x
Represents a hexadecimal integer using lowercase letters (a-f).
>>> number = 15 >>> print("%i in hex is %02x" % (number, number)) 15 in hex is 0f
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
By using the «02» prefix in our placeholder, we’re telling Python to print a two-character hex string.
%X
Represents a hexadecimal integer using uppercase letters (A-F).
>>> number = 15 >>> print("%i in hex is %04X" % (number, number)) 15 in hex is 000F
And like the previous example, by using the «04» prefix in our placeholder, we’re telling Python to print a four-character hex string.
%e
Represents an exponential notation with a lowercase «e».
%E
Represents an exponential notation with an uppercase «e».
%f
Represents a floating point real number.
>>> price = 15.95 >>> print("the price is %.2f" % price) the price is 15.95
%g
The shorter version of %f and %e .
%G
The shorter version of %f and %E .
The placeholders shown above allow you to format strings by specifying data types in your templates. However, these aren’t the only features of the interpolation operator. In the next subsection we’ll see how we can pad our strings with spaces using the % operator.
Aligning the Output
Up until now we’ve only shown how to format text strings by specifying simple placeholders. With the help of an additional numerical value, you can define the total space that shall be reserved on either side of a variable in the output string.
As an example the value of %10s reserves 10 characters, with the extra spacing on the left side of the placeholder, and a value of %-10s puts any extra space to the right of the placholder. The single padding character is a space, and cannot be changed.
>>> place = "London" >>> print ("%10s is not a place in France" % place) # Pad to the left London is not a place in France >>> print ("%-10s is not a place in France" % place) # Pad to the right London is not a place in France
Dealing with numbers works in the same way:
>>> print ("The postcode is %10d." % 25000) # Padding on the left side The postcode is 25000. >>> print ("The postcode is %-10d." % 25000) # Padding on the right side The postcode is 25000 .
Truncating strings and rounding numbers is the counterpart to padding. Have a look at Rounding Numbers in Python in order to learn more about the traps that are hiding here.
Conclusion
In this article we saw how the interpolation (aka formatting) operator is a powerful way to format strings, which allows you to specify data type, floating point precision, and even spacing/padding.