Python - Comparison to the % Formatting Expression

Description

Comparison to the % Formatting Expression

Demo

print('%s=%s' % ('test', 42))            # Format expression: in all 2.X/3.X 
print('{0}={1}'.format('test', 42))      # Format method: in 3.0+ and 2.6+ 
print('{}={}'.format('test', 42))        # With auto-numbering: in 3.1+ and 2.7
# from  ww  w  . ja v  a2  s  . com

Result

% expression can't handle keywords, attribute references, and binary type codes.

Demo

import sys
print( '%s, %s and %s' % (3.14, 42, [1, 2]) )                      # Arbitrary types 
print( 'My %(kind)s runs %(platform)s' % {'kind': 'laptop', 'platform': sys.platform} )
print( 'My %(kind)s runs %(platform)s' % dict(kind='laptop', platform=sys.platform) )

somelist = list('TEST') 
parts = somelist[0], somelist[-1], somelist[1:3] 
print( 'first=%s, last=%s, middle=%s' % parts )

# Adding specific formatting 
# www. j av a2s . c o  m
print( '%-10s = %10s' % ('test', 123.4567) )
print( '%10s = %-10s' % ('test', 123.4567) )
print( '%(plat)10s = %(kind)-10s' % dict(plat=sys.platform, kind='laptop') )

# Floating-point numbers 

print( '%e, %.3e, %g' % (3.14159, 3.14159, 3.14159) )

print( '%f, %.2f, %06.2f' % (3.14159, 3.14159, 3.14159) )

# Hex and octal, but not binary (see ahead) 

print( '%x, %o' % (255, 255) )

Result

The following code shows the same result generated with both techniques, with field sizes and justifications and various argument reference methods:

Demo

# Hardcoded references in both 
import sys 

print( 'My {1[kind]:<8} runs {0.platform:>8}'.format(sys, {'kind': 'laptop'}) )
print( 'My %(kind)-8s runs %(plat)8s' % dict(kind='laptop', plat=sys.platform) )

Result

Related Topic