Friday, January 20, 2012

Python Note 4( String Formatting)

Code
import math 

for x in range(1,20) :
 print ("{0:2d} {1:3d} {2:5d}".format(x,x*2,x*3))
 
tmplate="My {} is {}"
print(tmplate.format("country","Sri Lanka"))
print(tmplate.format("name","Kanishka"))

tmplate="Hello {name} , your role is {role}"
print(tmplate.format(name="Kanishka",role="Admin"))
print(tmplate.format(name="Sampath",role="User"))

print("The value of 'PI' is approximately {0:0.3f}".format(math.pi))
print("The value of 'e' is approximately {0:0.5f}".format(math.e))

#old formatting
print('The value of PI is approximately %5.3f' % math.pi)
Result



C:\Users\Kanishka\Desktop>python formatting.py
 1   2     3
 2   4     6
 3   6     9
 4   8    12
 5  10    15
 6  12    18
 7  14    21
 8  16    24
 9  18    27
10  20    30
11  22    33
12  24    36
13  26    39
14  28    42
15  30    45
16  32    48
17  34    51
18  36    54
19  38    57
My country is Sri Lanka
My name is Kanishka
Hello Kanishka , your role is Admin
Hello Sampath , your role is User
The value of 'PI' is approximately 3.142
The value of 'e' is approximately 2.71828
The value of PI is approximately 3.142

0 comments:

Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis