The following was obtained from ebeab.com
In [5]:
# define variables
x = 3.1415926
y = 1
In [3]:
# 2 decimal places
print "{:.2f}".format(x)
In [4]:
# 2 decimal palces with sign
print "{:+.2f}".format(x)
In [5]:
# 2 decimal palces with sign
print "{:.2f}".format(-y)
In [1]:
# print with no decimal palces
print "{:.0f}".format(3.51)
In [2]:
# left padded with 0's - width 4
print "{:0>4d}".format(11)
In [3]:
# print consecutive zero-padded numbers
for i in range(20):
print "{:0>4d}".format(i)
In [9]:
# right padd with x's - total width 4
print "{:x<4d}".format(33)
In [6]:
# right padd with x's - total width 4
print y
print "{:x<4d}".format(10*y)
In [11]:
# insert a comma separator
print "{:,}".format(10000000000000)
In [12]:
# % format
print "{:.4%}".format(0.1235676)
In [13]:
# exponent notation
print "{:.3e}".format(10000000000000)
In [8]:
# right justified, with 10
print '1234567890' # for place holders
print "{:10d}".format(10000000)
In [1]:
# left justified, with 10
print '0----5----0----5----0' # place holder
print "{:<10d}".format(100), "{:<10d}".format(100)
In [16]:
# center justified, width 10
print '1234567890'
print "{:^10d}".format(100)
In [9]:
# string substitution
s1 = 'so much depends upon {}'.format('a red wheel barrow')
s2 = 'glazed with {} water beside the {} chickens'.format('rain', 'white')
print s1
print s2
In [10]:
# another substitution
s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
print s1
print s2
In [13]:
## defining formats
email_f = "Your email address was {email}".format
print email_f
## use elsewhere
var1 = "bob@example.com"
var2 = 'a@cox.net'
var3 = 'b@cox.net'
print(email_f(email=var1))
print(email_f(email=var2))
print(email_f(email=var3))
In [ ]: