Thursday, November 8, 2012

Data types in python

You can use "isinstance" method to check the data type.

You can use "str" and "int" as a method to data type changes.
strint = "32"
if isinstance(strint, str):
    print "String"
    print int(strint)
    
x = 10    
print str(x)
print `x`
print "%d" % x

print int('10')
String
32
10
10
10
10

Iterator in python

You can make any class in a python utterable using iterator.
class IterTest:
    def __init__(self, itemList):
        self.itemList = itemList
        self.reset()

    def __iter__(self):
        return self
        
    def next(self):
        try:
            result = self.itemList[self.index]
        except IndexError:
            raise StopIteration
        self.index += 1
        return result       
        
    def reset(self):
        self.index = 0
        
        
if __name__ == "__main__":
    iterTest = IterTest([[1,3], [2,4]])
    for item in iterTest:
        print item
        
    iterTest.reset()
    for item in iterTest:
        print item      

References

python map and filter

Python's functional programming has two important method - map and filter. map has an input of a list, and iterates over the elements by applying a method.

filter uses the method given to filter out the elements that returns true when applying the method.

This is an example.
pair = \
[
{'group': 'b', 'method': 'test'},
{'group': 'a', 'method': 'test'}
]

print map(lambda x: x['group'] == 'a', pair)
print filter(lambda x: x['group'] == 'a', pair)
This is the result.
[False, True]
[{'group': 'a', 'method': 'test'}]

NULL check in SQLite

When you want to select only the data where comment is not null, you can use this command.
SELECT * from timeobject where comment != ""; 

References

http://stackoverflow.com/questions/7519621/where-is-null-not-working-in-sqlite

string concat with php

You can use dot for concatenating strings.

References

http://php.net/manual/en/language.operators.string.php