numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]                                                                                                                                                   
                                                                                                                                                                                                
for x in numbers:                                                                                                                                                                               
    print("{:10.4f}".format(x)) 

prints

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • The empty string before the colon means "take the next provided argument to format()" โ€“ in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.
Answer from Sven Marnach on Stack Overflow
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Format Strings and Numbers in Python: format() | note.nkmk.me
May 18, 2023 - If e is specified, the output will ...0.0001234)) # 1.234000e-04 # 1.234000E-04 ... As with f and F, you can specify the number of digits following the decimal point....
Discussions

string - How do I format a number with a variable number of digits in Python? - Stack Overflow
This is exactly what I'm looking for, I just do '123'.zfill(m) which allows me to use a variable instead of having a predetermined number of digits. Thanks! 2010-07-12T13:32:06.04Z+00:00 ... With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python string formatting with 'n' number of digits (when using keys) Python 2.7 - Stack Overflow
All you have to do is put the format specifier inside the formatting expression, separated from the field name/number by a colon. In this case, you could use {value1:02d}, where 02d is the code to get a zero-filled (0) width-2 (2) representation of an integer (d). ... Sign up to request clarification or add additional context in comments. ... This is surely a more pythonic way than the other one. 2017-11-27T02:43:46.017Z+00:00 ... The new string ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Format numbers to strings in Python - Stack Overflow
There are multiple ways of using this function, so for further information you can check the documentation. f-strings is a new feature that has been added to the language in Python 3.6. This facilitates formatting strings notoriously: More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I impose the total number of digits in python (new formatting) - Stack Overflow
I would like to keep the total number of digits (before and after the decimal point) of a float constant in python. For example, if I want to impose a fixed width of 7: 1234.567890123 would become... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ string.html
Common string operations โ€” Python 3.14.3 documentation
The precision is a decimal integer indicating how many digits should be displayed after the decimal point for presentation types 'f' and 'F', or before and after the decimal point for presentation types 'g' or 'G'. For string presentation types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer presentation types. The grouping option after width and precision fields specifies a digit group separator for the integral and fractional parts of a number respectively.
๐ŸŒ
The Teclado Blog
blog.teclado.com โ€บ python-formatting-numbers-for-printing
Formatting Numbers for Printing in Python - The Teclado Blog
March 23, 2023 - To specify a level of precision, we need to use a colon (:), followed by a decimal point, along with some integer representing the degree of precision. We place this inside the curly braces for an f-string, after the value we want to format.
๐ŸŒ
Linux find Examples
queirozf.com โ€บ entries โ€บ python-number-formatting-examples
Python number formatting examples
August 2, 2023 - # make the total string size AT LEAST 9 (including digits and points), fill with zeros to the left '{:0>9}'.format(3.499) # >>> '00003.499' # make the total string size AT LEAST 2 (all included), fill with zeros to the left '{:0>2}'.format(3) # >>> '03' Example make the full size equal to 11, filling with zeros to the right: ... In some Python versions such as 2.6 and 3.0, you must specify positional indexes in the format string:
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ formatting strings and numbers in python
Formatting strings and numbers in python | Towards Data Science
January 28, 2025 - We can use the fortmat() string function in python to output the desired text in the order we want. ... Now extending the formatting using f keyword ( look at the piece above ) , lets try to use that in numbers, particularly involving decimals ...
Find elsewhere
๐ŸŒ
Cheatography
cheatography.com โ€บ brianallan โ€บ cheat-sheets โ€บ python-f-strings-number-formatting
Python F-Strings Number Formatting Cheat Sheet by BrianAllan - Download free from Cheatography - Cheatography.com: Cheat Sheets For Every Occasion
Contains formulas, tables, and examples showing patterns and options focused on number formatting for Python's Formatted String Literals -- i.e., F-Strings.
Rating: 0 โ€‹ - โ€‹ 2 votes
๐ŸŒ
Python Course
python-course.eu โ€บ python-tutorial โ€บ formatted-output.php
22. Formatted Output | Python Tutorial | python-course.eu
November 8, 2023 - The format string contains placeholders. There are two of those in our example: "]" and "%8.2f". ... 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 ...
๐ŸŒ
mkaz.blog
mkaz.blog โ€บ working-with-python โ€บ string-formatting
Python String Formatting: Complete Guide
The % formatting method is Pythonโ€™s oldest string formatting approach, but itโ€™s error-prone and less readable than modern alternatives. ... # ERROR: Type mismatch name = "Alice" age = 25 try: result = "Name: %d, Age: %s" % (name, age) # Wrong types! except TypeError as e: print(f"Error: {e}") # TypeError: %d format: a number is required, not str # FIX: Use correct format specifiers result = "Name: %s, Age: %d" % (name, age) print(result) # Name: Alice, Age: 25 # ERROR: Wrong number of arguments try: result = "%s and %s living together" % ("cats",) # Missing argument except TypeError as e: print(f"Error: {e}") # TypeError: not enough arguments for format string # FIX: Provide all required arguments result = "%s and %s living together" % ("cats", "dogs") print(result) # cats and dogs living together
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ functions โ€บ format.html
format โ€” Python Reference (The Right Way) 0.1 documentation
This is the default type for strings and may be omitted. ... The same as โ€˜sโ€™. The available integer presentation types are: โ€˜bโ€™ ยท Binary format. Outputs the number in base 2. ... Character. Converts the integer to the corresponding unicode character before printing. ... Decimal Integer. Outputs the number in base 10. ... Octal format. Outputs the number in base 8. ... Hex format. Outputs the number in base 16, using lower- case letters for the digits ...
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ string.html
6.1. string โ€” Common string operations โ€” Python 3.4.10 documentation
This is equivalent to a fill character of '0' with an alignment type of '='. The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content.
Top answer
1 of 9
159

Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:

hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'

or the str.format function starting with 2.7:

"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")

or the string formatting % operator for even older versions of Python, but see the note in the docs:

"%02d:%02d:%02d" % (hours, minutes, seconds)

And for your specific case of formatting time, thereโ€™s time.strftime:

import time

t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
2 of 9
103

The OP & accepted answer focus on formatting time, but the OP question itself discusses formatting numbers to strings in Python. In many cases, the output requires additional data fields be included along with timestamps, all of which include formatting numbers as strings.

Below are a variety of non time-based examples of formatting numbers as strings, and different ways to do so, starting with the existing string format operator (%) which has been around for as long as Python has been around (meaning this solution is compatible across Python 1.x, 2.x, and 3.x):

>>> "Name: %s, age: %d" % ('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 
'dec: 45/oct: 055/hex: 0X2D' 
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 
'http://xxx.yyy.zzz/user/42.html' 

Starting in Python 2.6 (meaning it works for 2.x and 3.x), there is an alternative: the str.format() method. Here are the equivalent snippets to the above but using str.format():

>>> "Name: {0}, age: {1}".format('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) 
'dec: 45/oct: 0o55/hex: 0X2D' 
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 
'http://xxx.yyy.zzz/user/42.html'

Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of my hardcore Python intro book and the slides for the Intro+Intermediate Python courses I offer from time-to-time. :-)

Aug 2018 UPDATE: Of course, now that we have the f-string feature introduced in 3.6 (only works in 3.6 and newer), we need the equivalent examples of that; yes, another alternative:

>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'

>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'

>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'

>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'

>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
๐ŸŒ
Real Python
realpython.com โ€บ how-to-python-f-string-format-float
How to Format Floats Within F-Strings in Python โ€“ Real Python
April 24, 2024 - See if you can rewrite this using the f-string syntax. Task 9: Start with the numbers = [1234.56789, 123.456789, 12.3456789, 1.23456789] list, and see if you can write a format specifier to produce a second list named numbers_formatted that contains ["1,234.5679", "123.457", "12.35", "1.2"]. As you can see, each number is rounded so that there are the same number of digits before the decimal point as there are after it.
Top answer
1 of 3
3

Just by using your example,

a = 1234.567890123 
b = 12345.678901234
str(a)[:8] # gives '1234.567'
str(b)[:8] # gives '12345.67'
2 of 3
0

The simplest solution is probably to use the exponential format with one less than the number of digits.

"{0:.6e}".format(1234.457890123) = '1.234568e+03'

I ended up writing this solution that can print floats as well as exponentials but it's probably unnecessarily long for most needs.

 import numpy as np

 def sigprint(number,nsig):
     """
     Returns a string with the given number of significant digits.
     For numbers >= 1e5, and less than 0.001, it does exponential notation
     This is almost what ":.3g".format(x) does, but in the case
     of '{:.3g}'.format(2189), we want 2190 not 2.19e3. Also in the case of
     '{:.3g}'.format(1), we want 1.00, not 1
     """

     if ((abs(number) >= 1e-3) and (abs(number) < 1e5)) or number ==0:
         place = decplace(number) - nsig + 1
         decval = 10**place
         outnum = np.round(np.float(number) / decval) * decval
         ## Need to get the place again in case say 0.97 was rounded up to 1.0
         finalplace = decplace(outnum) - nsig + 1 
         if finalplace >= 0: finalplace=0
         fmt='.'+str(int(abs(finalplace)))+'f'
     else:
         stringnsig = str(int(nsig-1))
         fmt = '.'+stringnsig+'e'
         outnum=number
     wholefmt = "{0:"+fmt+"}"

     return wholefmt.format(outnum)

 def decplace(number):
     """
     Finds the decimal place of the leading digit of a number. For 0, it assumes
     a value of 0 (the one's digit)
     """
     if number == 0:
         place = 0
     else:
         place = np.floor(np.log10(np.abs(number)))
     return place
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ format
Python format()
Here, format(123, 'd') and format(123, 'b') converts the integer 123 to its decimal and binary string representation respectively. Note: We have used format specifiers, d for decimal and b for binary. To learn more about format types, visit Format Types. ... Alignment in formatting refers to ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python format float to string
How to Format a Floating Number to String in Python | Delft Stack
February 2, 2024 - In this code, we have a floating-point number num initialized with the value 0.02893574. Using the % operator and the format specifier "%.4f", we print the value of num to the console with a fixed width of four decimal places. The % operator acts as a placeholder for the variable num in the format string, and the .4f specifies that we want to display exactly four digits after the decimal point.
๐ŸŒ
Johnlekberg
johnlekberg.com โ€บ blog โ€บ 2020-06-27-number-fmt.html
Formatting numbers in Python
Another nice feature of the format specifier is that it can group digits in large numbers. For example, I have 230 ... Exponent notation (e.g. 2 ** 30 becomes 1.073742e+09). Percentages (e.g. .32 becomes 32%). I highly recommend you read the Python documentations "Format Specification Mini-Language" to learn about all of the different capabilities. Besides calling the built-in function format(), you can also use str.format() and formatted string literals (also called "f-strings").
๐ŸŒ
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples. All examples on this page work out of ...