Python – check variable for None

 

To check if a variable is None use following code:

>>> val=None
>>> val is None
True

If you want to use above example with if condition use following code:

if not (val in None):
  print "val is not none"
else:
  print "val is none"
Advertisements

Python – ImportError: No module named memcache

While trying to connect memcached using python I got following error:

ImportError: No module named memcache

Since I imported memcache & it’s not available in my server I got the error message saying that “No module named memcache”.

To resolve this issue we need to install python-memcache module.

Use following command to install python-memcache:

$ pip install python-memcache

If  your OS is Ubuntu/Debian following command also works for you:

$ apt-get install python-memcache

After installing python-memcache we can seamlessly connect to memcached.

fatal error: Python.h: No such file or directory

While trying to install some python module I got following exception:

fatal error: Python.h: No such file or directory

Reason for exception:

If you haven’t properly installed the header files and static libraries for python dev this issue may occur.

To resolve this issue install python-dev module by using following command:

$ sudo apt-get install python-dev

Python – check if ip is public or private

 

netaddr is a Python library for representing and manipulating network addresses.

Installing netaddr library:

Use any of following command to install netaddr library

$ sudo pip install netaddr
or
$ easy_install netaddr

Observe following example for more details:

>>> from netaddr import *
>>> IPAddress('74.125.236.194').is_private()
False
>>> IPAddress('192.168.1.10').is_private()
True
>>> IPAddress('127.0.0.1').is_loopback()
True

IPAddress(‘input ip’).is_private() will return true if the input ip address private, else it will return false.

Reference: Netaddr

Python – find files in directory with extension

The glob module finds all the pathnames matching a specific pattern according to the rules used by the Unix Shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

Examples:

To list all files ending with *.txt in /home/guest directory:

>>> import glob
>>> glob.glob("/home/guest/*.txt")

Output:
[‘/home/guest/syslog.txt’, ‘/home/guest/mysql.txt’, ‘/home/guest/topics.txt’, ‘/home/guest/bus.txt’]

Similarly you can try others.

As mentioned above No tilde expansion will work, so following example will return empty list.

>>> glob.glob("~/guest/*.txt")

Output:
[]

Python – get system hostname

 

By using socket.gethostname() we can get hostname of system:

>>> import socket
>>> socket.gethostname()
'localhost'

There is one more way to get hostname is by using platform.node():

>>> import platform
>>> platform.node()
'localhost'

Python – count duplicates in list

 

By using python collections.Counter(<LIST>) we can count number of duplicates in list.

Observer following example for more details:

>>> import collections
>>> mylist = ['a', 'b', 'a', 'c', 'a', 'b']
>>> uniqCount = collections.Counter(mylist)
>>> uniqCount
Counter({'a': 3, 'b': 2, 'c': 1})
>>> uniqCount.keys()
['a', 'c', 'b']
>>> uniqCount.values()
[3, 1, 2]

Python reverse a string with slicing

 

In python there is no direct function to reverse a string, to reverse a string we need to use slicing.

A slice extracts elements based on a start.
An extended slice extracts elements based on start and stop with step/stride.

Some examples of slicing:

>>> values="abcdefg"
>>> values[1:3]
'bc'
>>> values[2:-1]
'cdef'
>>> values[:2]
'ab'
>>> values[2:]
'cdefg'
>>> values[::2]
'aceg'
>>> values[::-1]
'gfedcba'

Slicing can be used for strings, lists, tuples, arrays and custom data structures as well.

If you observer above example the last slice values[::-1] is printing reverse string where we are using extended slicing.

>>> values[::-1]
'gfedcba'
>>> 'xyz'[::-1]
'xyz'

Syntax of extended slice:

[begin:end:step]

In our example by leaving begin and end off and specifying a step of -1 will reverses a string.

Python – check if value/variable is integer

 

By using is isinstance(var, type) function we can check a given value/variable is integer or not. isinstance will either written True or False.

Here is and an example:

>>> isinstance(10, int)
True
>>> var_a=10
>>> isinstance(var_a, int)
True
>>> isinstance('a', int)
False

To check if variable is a number use following example:

>>> isinstance(1.0, (int, long, float))
True