Basic Formatting

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)


3.14

In [4]:
# 2 decimal palces with sign
print "{:+.2f}".format(x)


+3.14

In [5]:
# 2 decimal palces with sign
print "{:.2f}".format(-y)


-1.00

In [1]:
# print with no decimal palces
print "{:.0f}".format(3.51)


4

In [2]:
# left padded with 0's - width 4
print "{:0>4d}".format(11)


0011

In [3]:
# print consecutive zero-padded numbers
for i in range(20):
    print "{:0>4d}".format(i)


0000
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019

In [9]:
# right padd with x's - total width 4
print "{:x<4d}".format(33)


33xx

In [6]:
# right padd with x's - total width 4
print y
print "{:x<4d}".format(10*y)


1
10xx

In [11]:
# insert a comma separator
print "{:,}".format(10000000000000)


10,000,000,000,000

In [12]:
# % format
print "{:.4%}".format(0.1235676)


12.3568%

In [13]:
# exponent notation
print "{:.3e}".format(10000000000000)


1.000e+13

In [8]:
#  right justified, with 10
print '1234567890' # for place holders
print "{:10d}".format(10000000)


1234567890
  10000000

In [1]:
#  left justified, with 10
print '0----5----0----5----0' # place holder
print "{:<10d}".format(100), "{:<10d}".format(100)


0----5----0----5----0
100        100       

In [16]:
#  center justified, width 10
print '1234567890'
print "{:^10d}".format(100)


1234567890
   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


so much depends upon a red wheel barrow
glazed with rain water beside the white chickens

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


 emacs is better than vim 
 vim is better than emacs 

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))


<built-in method format of str object at 0x7fd474115198>
Your email address was bob@example.com
Your email address was a@cox.net
Your email address was b@cox.net

In [ ]: