Python

Published: Sunday, 25 January 2015

Python is a scripting language.

There are two versions, 2.x and 3.x

main

Use the __name__ parameter to determine if you are calling your script from the command line.

#!/usr/bin/python

__author__ = 'magicmonster'

def main():
    print __name__

if __name__ == "__main__":
    main()

Modules

import

Before using a module you must import it. e.g. if you want to use the sys module, add the following to the top of your python script file.

import sys

args

Command line arguments are accessible via sys.argv. As with C, argv[0] contains your script file.

Strings

Join

You can join a list of strings to make one string.

long_string = ",".join(["apple","banana","carrot"])

Casting

To convert an int into a string, use str

String value present in a set

Use the in operator to test whether a value is present in a set.

>>> 'apple' in ('apple','pear','banana')
True

trim

Use stripinstead. e.g. to trim a trailing slash, use rstrip

>>> "dir/".rstrip("/")
'dir'

Built-in functions

len

len returns the length of a String or array.

>>> len("apple")
5
>>> len(["red", "green"])
2

Classes

It is possible to define a class that holds state.