8.2.3 Numeric Formatting

Formatting Positive Numbers with Signs

  • A + before the field width specifies that a positive number should be preceded by a +
  • To fill the remaining characters of the field with 0s rather than spaces, place a 0 before the field width (and after the + if there is one)
In [1]:
f'[{27:+10d}]'
Out[1]:
'[       +27]'
In [2]:
f'[{27:+010d}]'
Out[2]:
'[+000000027]'

Using a Space Where a + Sign Would Appear in a Positive Value

  • A space indicates that positive numbers should show a space character in the sign position
In [3]:
print(f'{27:d}\n{27: d}\n{-27: d}')
27
 27
-27

Grouping Digits

  • Format numbers with thousands separators by using a comma (,)
In [4]:
f'{12345678:,d}'
Out[4]:
'12,345,678'
In [5]:
f'{123456.78:,.2f}'
Out[5]:
'123,456.78'

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.