Python - String Formatting Method Advanced Examples

Introduction

{0:10} means the first positional argument in a field 10 characters wide.

{1:<10} means the second positional argument left-justified in a 10-character-wide field.

{0.platform:>10} means the platform attribute of the first argument right-justified in a 10-character-wide field:

Demo

import sys
print( '{0:10} = {1:10}'.format('test', 123.4567) )         # In Python 3.3 
# w w  w .j  a va  2s  . c  om
print( '{0:>10} = {1:<10}'.format('test', 123.4567) )

print( '{0.platform:>10} = {1[kind]:<10}'.format(sys, dict(kind='laptop')) )

Result

You can omit the argument number if you're selecting them from left to right with relative auto-numbering.

Demo

import sys
print( '{:10} = {:10}'.format('test', 123.4567) )
print( '{:>10} = {:<10}'.format('test', 123.4567) )
print( '{.platform:>10} = {[kind]:<10}'.format(sys, dict(kind='laptop')) )

Result

Floating-point numbers support the same type codes and formatting specificity in formatting method calls as in % expressions.

{2:g} means the third argument formatted by default according to the "g" floating-point representation

{1:.2f} designates the "f" floating-point format with just two decimal digits,

{2:06.2f} adds a field with a width of six characters and zero padding on the left:

Demo

print( '{0:e}, {1:.3e}, {2:g}'.format(3.14159, 3.14159, 3.14159) )
print( '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159) )

Result

Related Topic