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

Thursday, January 16, 2014

python filter(), map(), reduce() with list

  • filter(function, sequence) : returns sequence for which function(item) is true
  • map(function, sequence): call function(item) for each item and returns a list
  • reduce(function, sequence): returns a single value constructed by calling function on first two items on the sequence, then the result and the next item, and so on.
def f(x):
    return x % 2 == 0
print filter(f, range(1,10))


def square(x):
    return x*x
print map(square, range(1,5))

def add(x, y):
    return x+y
print reduce(add, range(1,10))

Output:
[2, 4, 6, 8]
[1, 4, 9, 16]
45

Unicode in python

Python unicode example: code format '\uXXXX'

For more unicode follow http://unicode-table.com/en/#0985
a = u'Hello: \u0061'
print a

a = u'Hello: \u0985'
print a

a = u'Hello: \u0995'
print a

Output:
Hello: a
Hello: অ
Hello: ক

Tuesday, January 14, 2014

Python array declaration by type

Python provides array declaration of specific types(ex-int, float, char). It is much faster(~10x) than normal array. Lets go to the code.

import array

# integer array declaration
a_int = array.array('i')
a_int.append(5)  # Error a_int.append(5.5)
print a_int[0]
a_int = array.array('i', range(10))
print a_int[7]

# float array declaration
a_float = array.array('f')
a_float.append(10)
print a_float[0]

# character array declaration
a_char = array.array('c')
a_char.append('A')
print a_char[0]

a_char = array.array('c', "python")
print a_char[1]

Output:
5
7
10.0
A
y