Integer Output
%o
—Octal (Base 8)%d
—Decimal (Base 10)%x
—Hexadecimal (Base 16)
Floating-Point (Decimal) Output
Formatted Output
>>> awsl = 2.333
>>> print('%f' % awsl) # Default to 6 decimal places
2.333000
>>> print('%.1f' % awsl) # Round to 1 decimal place
2.3
>>> print('%e' % awsl) # Scientific notation, 6 decimal places by default
2.333000e+00
>>> print('%.2e' % awsl) # Scientific notation, 2 decimal places
2.33e+00
>>> print('%g' % 2.3333333) # Up to 6 significant figures
2.33333
>>> print('%.5g' % 233.33333) # 5 significant figures
233.33
>>> print('%.2g' % 2333.3333) # 2 significant figures, auto scientific notation
2.3e+03
Built-in round()
round(number[, ndigits])
- Parameters:
number
: The number to round.ndigits
: The number of decimal places to round to. Defaults to0
.
- Return Value: The rounded value of
number
tondigits
decimal places. - If
round()
is called with a single argument, it rounds to the nearest integer. - When a specific decimal place is specified, the function usually follows standard rounding rules.
- Special case: When rounding
.5
, Python rounds to the nearest even number.
Note:.5
rounding behavior can be tricky, and round()
may yield different results between Python 2 and Python 3. Avoid relying on it in critical applications.
>>> round(1.1125) # Round to nearest integer
1
>>> round(1.1135, 3) # Round to 3 decimal places; 3 is odd, so round down
1.113
>>> round(1.1125, 3) # Round to 3 decimal places; 2 is even, so round up
1.113
>>> round(2.675, 2) # Round to 2 decimal places
2.67
Explanation of round(2.675, 2)
Result: Although the result seems incorrect (2.67
instead of 2.68
), this behavior arises from floating-point precision. Internally, the binary representation of 2.675
is slightly less than the actual value, causing it to round to 2.67
.
String Output
%s
%10s
—Right-aligned, occupying 10 spaces%-10s
—Left-aligned, occupying 10 spaces%.2s
—Extract 2 characters%10.2s
—Right-aligned, occupying 10 spaces, extract 2 characters
>>> print('%s' % 'hello world') # String output
hello world
>>> print('%20s' % 'hello world') # Right-aligned, 20 spaces
hello world
>>> print('%-20s' % 'hello world') # Left-aligned, 20 spaces
hello world
>>> print('%.2s' % 'hello world') # Extract 2 characters
he
>>> print('%10.2s' % 'hello world') # Right-aligned, extract 2 characters
he
>>> print('%-10.2s' % 'hello world') # Left-aligned, extract 2 characters
he
Outputting Multiple Variables
>>> hhh = 2333
>>> awsl = 2.333
>>> print('%d + %f = %f' % (hhh, awsl, hhh + awsl))
2333 + 2.333000 = 2335.333000
Comprehensive List of Format Specifiers
Symbol | Description |
---|---|
%c | Character or ASCII value |
%s | String |
%d | Integer |
%u | Unsigned integer |
%o | Unsigned octal |
%x | Unsigned hexadecimal (lowercase) |
%X | Unsigned hexadecimal (uppercase) |
%f | Floating-point number with specified precision |
%e | Scientific notation (lowercase 'e') |
%E | Scientific notation (uppercase 'E') |
%g | Compact representation of float (removes trailing zeros) |
%G | Similar to %g with uppercase letters for scientific notation |
%p | Pointer (memory address in hexadecimal) |
Auxiliary Instructions for Formatting Operators:
Symbol | Description |
---|---|
* | Defines width or decimal precision |
- | Used for left alignment |
+ | Displays a plus sign (+) before positive numbers |
Displays a space before positive numbers | |
# | Prefixes octal numbers with '0' and hexadecimal numbers with '0x' or '0X' (depending on whether 'x' or 'X' is used) |
0 | Pads numbers with zeros instead of spaces |
% | Outputs a single '%' with '%%' |
(var) | Maps variables (dictionary arguments) |
m.n. | m specifies the minimum total width, and n specifies the number of decimal places (if applicable) |
Using format
Compared to basic formatted output with %
, the format()
function is more powerful. It treats strings as templates and formats them using the parameters passed, with {}
used as placeholders instead of %
.
Positional Matching
- Without an index, i.e.,
{}
. - With numbered indices, allowing reordering, i.e.,
{1}
,{2}
. - With keywords, i.e.,
{a}
,{tom}
.
>>> print('{} {}'.format('zeruns', 'blog.zeruns.com')) # No index
zeruns blog.zeruns.com
>>> print('{0} {1}'.format('hello', 'world')) # With numbered indices
hello world
>>> print('{1}{0}'.format('blog.zeruns.com', 'https://'))
https://blog.zeruns.com
>>> print('{0} {1} {0}'.format('hello', 'world')) # Reordered
hello world hello
>>> print('{1} {1} {0}'.format('hello', 'world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello', a='world')) # With keywords
world hello world
# Using positional matching
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # Supported in Python 3.1+
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # Can reorder
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # Can repeat
'abracadabra'
# Using name matching
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
# Matching parameters by index or key
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
>>> a = {'a': 'test_a', 'b': 'test_b'}
>>> 'X: {0[a]}; Y: {0[b]}'.format(a)
'X: test_a; Y: test_b'
Comment Section