Python string format Width and Precision

Control the Width and Precision

The width is the minimum number of characters reserved for a formatted value.

If the precision is for a numeric conversion then it sets the number of decimals that will be included in the result, If the precision is for a string conversion then it sets the maximum number of characters the formatted value may have.

These two parameters are supplied as two integer numbers (width first, then precision), separated by a .(dot). Both are optional, but if you want to supply only the precision, you must also include the dot:


print '%10f' % 3.1415926      # Field width 10 
print '%10.2f' % 3.1415926    # Field width 10, precision 2 
print '%.2f' % 3.1415926      # Precision 2 
print '%.5s' % 'www.java2s.com' 

The code above generates the following result.

You can use an * (asterisk) as the width or precision (or both), in which case the number will be read from the tuple argument:


print '%.*s' % (5, 'www.java2s.com') 

The code above generates the following result.

Five digits after decimal in float


floatValue = 123456.789

print "Five digits after decimal in float %.5f" % floatValue

The code above generates the following result.

Fifteen and five characters allowed in string


stringValue = "String formatting"
# from w ww .j  a v  a 2 s.  c o m
print "Fifteen and five characters allowed in string:"

print "(%.15s) (%.5s)" % ( stringValue, stringValue )

The code above generates the following result.

Force eight digits in integer


integerValue = 4237

print "Force eight digits in integer %.8d" % integerValue

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary