Python format output float

21. Formatted Output

In this chapter of our Python tutorial we will have a closer look at the various ways of creating nicer output in Python. We present all the different ways, but we recommend that you should use the format method of the string class, which you will find at end of the chapter. «string format» is by far the most flexible and Pythonic approach.

So far we have used the print function in two ways, when we had to print out more than two values:

The easiest way, but not the most elegant one:

We used print with a comma separated list of values to print out the results, as we can see in the following example. All the values are separated by blanks, which is the default behaviour. We can change the default value to an arbitrary string, if we assign this string to the keyword parameter «sep» of the print function:

q = 459 p = 0.098 print(q, p, p * q) 

OUTPUT:

OUTPUT:

OUTPUT:

Alternatively, we can construe a new string out of the values by using the string concatenation operator:

print(str(q) + " " + str(p) + " " + str(p * q)) 

OUTPUT:

The second method is inferior to the first one in this example.

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

The Old Way or the non-existing printf and sprintf

Traditional Output with movable types

Is there a printf in Python? A burning question for Python newbies coming from C, Perl, Bash or other programming languages who have this statement or function. To answer «Python has a print function and no printf function» is only one side of the coin or half of the truth. One can go as far as to say that this answer is not true. So there is a «printf» in Python? No, but the functionality of the «ancient» printf is contained in Python. To this purpose the modulo operator «%» is overloaded by the string class to perform string formatting. Therefore, it is often called string modulo (or somethimes even called modulus) operator, though it has not a lot in common with the actual modulo calculation on numbers. Another term for it is «string interpolation», because it interpolates various class types (like int, float and so on) into a formatted string. In many cases the string created via the string interpolation mechanism is used for outputting values in a special way. But it can also be used, for example, to create the right format to put the data into a database. Since Python 2.6 has been introduced, the string method format should be used instead of this old-style formatting. Unfortunately, string modulo «%» is still available in Python3 and what is even worse, it is still widely used. That’s why we cover it in great detail in this tutorial. You should be capable of understanding it, when you encounter it in some Python code. However, it is very likely that one day this old style of formatting will be removed from the language. So you should get used to str.format().

Читайте также:  Java util list file

The following diagram depicts how the string modulo operator works:

General way of working of the string modulo operator

On the left side of the «string modulo operator» there is the so-called format string and on the right side is a tuple with the content, which is interpolated in the format string. The values can be literals, variables or arbitrary arithmetic expressions.

General way of working of the string modulo operator, format string

The format string contains placeholders. There are two of those in our example: «%5d» and «%8.2f».

The general syntax for a format placeholder is

Explaining a float format

Let’s have a look at the placeholders in our example. The second one «%8.2f» is a format description for a float number. Like other placeholders, it is introduced with the «%» character. This is followed by the total number of digits the string should contain. This number includes the decimal point and all the digits, i.e. before and after the decimal point. Our float number 59.058 has to be formatted with 8 characters. The decimal part of the number or the precision is set to 2, i.e. the number following the «.» in our placeholder. Finally, the last character «f» of our placeholder stands for «float».

If you look at the output, you will notice that the 3 decimal digits have been rounded. Furthermore, the number has been preceded in the output with 3 leading blanks.

The first placeholder «%5d» is used for the first component of our tuple, i.e. the integer 453. The number will be printed with 5 characters. As 453 consists only of 3 digits, the output is padded with 2 leading blanks. You may have expected a «%5i» instead of «%5d». Where is the difference? It’s easy: There is no difference between «d» and «i» both are used for formatting integers. The advantage or beauty of a formatted output can only be seen, if more than one line is printed with the same pattern. In the following picture you can see, how it looks, if five float numbers are printed with the placeholder «%6.2f» in subsequent lines:

Читайте также:  Html input type file accept images

formatting multiple floats

Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Obsolete and equivalent to ‘d’, i.e. signed integer decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as «e» if exponent is greater than -4 or less than precision, «f» otherwise.
G Same as «E» if exponent is greater than -4 or less than precision, «F» otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a «%» character in the result.

The following examples show some example cases of the conversion rules from the table above:

Источник

How to Format Float Values in Python

Here are 4 methods to format float in Python.

  1. Using the “format()” function
  2. Using the “%f” format specifier
  3. Using the “round()” function
  4. Using the “f-string” function

Method 1: Using the format() function

To format float values in Python, you can use the “format()” method. The format() method allows multiple substitutions and value formatting.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print("".format(z))

The output returns a string. To get the output as float, use the float() function.

x = 211911461911461819112146 y = 2**70 z = x / y print(float("".format(z)))

Method 2: Using the “%f” format specifier

To format the float value up to two decimal places in Python, you can use the “%.2f” format specifier inside the “print()” function.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print("%.2f" % z)

To format up to three decimal places, use the %.3f.

x = 211911461911461819112146 y = 2**70 z = x / y print("%.3f" % z)

You can see that when we are printing only two decimal places, it automatically rounds to the nearest integer.

Читайте также:  Propensity score matching python

Still, printing a number up to three decimal places does not go round to the nearest integer. The 0.496 prints as it is since we want a floating value up to three decimal places.

How to Use the %d Formatter in Python

You can also use floating point numbers in Python with the “%d” formatter. This returns the whole number in a floating point number.

floatNumber = 2.9876 print("%d" % floatNumber) 

Method 3: Using the round() function

The “round()” is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print(round(z, 2))

But please note that the behavior of the round() function for floats can be surprising in some cases. For example, round(3.575, 2) gives 3.57 instead of the expected 3.58.

This is not a bug: it’s a result that most decimal fractions can’t be represented exactly as a float.

Method 4: Using the Python f-strings

Python f-String is an improvement over previous formatting methods. You can read more at PEP8.

Let’s use the f-strings to format the float value.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print(f'')

It works well with long calculations with operators and does not need parenthesis.

Conclusion

You can use the %f format specifier or string.format() function to format the float values in Python. You can also use the round() method or the f-string approach.

Источник

Оцените статью