Python Tutorial

Friday, January 17, 2014

Python fancy string formatting

print "1. Life is {} {} {} python".format('very','easy', 'with')
print "2. Life is {0} {1} {2} python".format('very','easy', 'with')

print "3. Life is {1} {0} {2} python".format('very','easy', 'with')
print "4. Life is {1} {0} {t} python".format('very','easy', t='with')
print "5. Life is {0} {t} python".format('very easy', t='with')

for n in range(5, 11):
    print "{0:2d} {1:3d} {2:4d}".format(n, n*n, n*n*n)

d = {"name1":100, "name3":350, "name2":250}
print "6. First: {name1:d}, Second: {name2:d}, Third: {name3:d}".format(**d)

print "zfill pads string on left zeros, it also consider + and - sign"
print '25'.zfill(5)
print '2.5'.zfill(5)
print '-2.5'.zfill(5)
print '2.54234324234'.zfill(5)
print 'ah'.zfill(5)

print "asd".rjust(6, 'R')
print "asd".ljust(6, 'R')

Output:
1. Life is very easy with python
2. Life is very easy with python
3. Life is easy very with python
4. Life is easy very with python
5. Life is very easy with python
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
6. First: 100, Second: 250, Third: 350
zfill pads string on left zeros, it also consider + and - sign
00025
002.5
-02.5
2.54234324234
000ah
RRRasd
asdRRR

0 comments:

Post a Comment