Skip to content

Python

Python is a scripting language.

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

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()

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.

Terminal window
import sys

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

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

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

To convert an int into a string, use str

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

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

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

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

len returns the length of a String or array.

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

It is possible to define a class that holds state.