If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'

See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings

Here is an example with variable width

>>> '{num:0{width}}'.format(num=123, width=6)
'000123'

You can even specify the fill char as a variable

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
Answer from John La Rooy on Stack Overflow
๐ŸŒ
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.
๐ŸŒ
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....
๐ŸŒ
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 ...
๐ŸŒ
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:
๐ŸŒ
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
Find elsewhere
๐ŸŒ
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 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 ...
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'
๐ŸŒ
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.
๐ŸŒ
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 ...
๐ŸŒ
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
๐ŸŒ
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 ...
๐ŸŒ
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.
๐ŸŒ
Learn Python
learnpython.org โ€บ en โ€บ String_Formatting
String Formatting - Learn Python - Free Interactive Python Tutorial
The string which returns from the ... is formatted as the string. For example: # This prints out: A list: [1, 2, 3] mylist = [1,2,3] print("A list: %s" % mylist) Here are some basic argument specifiers you should know: %s - String (or any object with a string representation, like numbers) ... %.<number of digits>f - Floating ...