Python String format type conversion
Convert various types to string
Conversion type string
Letter | Meaning |
---|---|
d, i | Signed integer decimal |
o | Unsigned octal |
u | Unsigned decimal |
x | Unsigned hexadecimal (lowercase) |
X | Unsigned hexadecimal (uppercase) |
e | Floating point exponential format (lowercase) |
E | Floating point exponential format (uppercase) |
f, F | Floating point decimal format |
g | Same as e if exponent is greater than ?4 or less than precision, f otherwise |
G | Same as E if exponent is greater than ?4 or less than precision, F otherwise |
c | Single character (accepts integer or single character string) |
r | String (converts any Python object using repr) |
The simple conversion, with only a conversion type, is really easy to use:
print 'Price of eggs: $%d' % 42
print 'Hexadecimal price of eggs: %x' % 42
print 'Hexadecimal price of eggs: 2a'
print 'Pi: %f...' % 3.1415926
print 'Very inexact estimate of pi: %i' % 3.1415926
print 'Using str: %s' % 42L
print 'Using repr: %r' % 42L
# ww w . ja v a2 s .c o m
print "%x" % 108
print "%X" % 108
print "%o %x %X" % (64, 64, 255)
print '%.2f'%(1/3.0) # results in: '0.33'
print '%s'%(1/3.0) # results in: '0.333333333333'
The code above generates the following result.