Hex, octal, and binary formats are supported by the format method.
print( '{0:X}, {1:o}, {2:b}'.format(255, 255, 255) ) # Hex, octal, binary print( bin(255), int('11111111', 2), 0b11111111 ) # Other to/from binary print( hex(255), int('FF', 16), 0xFF ) # Other to/from hex print( oct(255), int('377', 8), 0o377 ) # Other to/from octal, in 3.X # w ww . j ava2 s. c om
Formatting parameters can hardcoded in format strings or taken from the arguments list, much like the * syntax in formatting expressions' width and precision:
print( '{0:.2f}'.format(1 / 3.0) ) # Parameters hardcoded print( '%.2f' % (1 / 3.0) ) # Ditto for expression # w ww . j a va 2s . c o m print( '{0:.{1}f}'.format(1 / 3.0, 4) )# Take value from arguments print( '%.*f' % (4, 1 / 3.0) ) # Ditto for expression
Using build-in function:
print( '{0:.2f}'.format(1.2345) )# String method print( format(1.2345, '.2f') ) # Built-in function print( '%.2f' % 1.2345 ) # Expression # from ww w . ja v a 2s . co m