Posts Tagged ‘Python’

There are a number of ways to print a number with zero-padding (leading zeros), depending on the variable type you are wanting to print. One easy way to add zero padding to any type is to use the str(<number>).zfill(<length>). This will convert any number type to a string before adding the extra zeros. For example: […]

HTTP GET request in Python

Posted: 28th September 2014 by Tim in Python
Tags: , , , , , ,

There are a number of ways to make a GET request in Python, but the easiest (in my opinion) is via urllib2. With this library, you can make a request with only one line of code, storing the result for use later. For example: import urllib2 data = urllib2.urlopen(“http://timmurphy.org”).read() print “Website size (bytes): ” + […]

FIFOs are a very simple tool for communicating between processes. And using them in python is very easy. Simply call os.mkfifo(<path>) and treat the FIFO like any other file. For example, we can create two simple python scripts, one for sending and one for receiving. sender.py import os path = “/tmp/my_program.fifo” os.mkfifo(path) fifo = open(path, […]

Strings in python can be split using any given delimeter. Unlike other languages, the delimeter can be a string of any length; it’s not limited to one character. To do this, you can use the <string>.split(<delimeter>) function. Similarly, you can join an array of strings back into one string, using any defined string to join […]

Reversing a string in Python

Posted: 25th April 2013 by Tim in Python
Tags: , , , , , , , ,

If you need to reverse a string in python, the easiest way is to do use the my_string[::-1] syntax. For example, to print a reversed string, you could write: my_string = “ABCDE” print my_string[::-1] So what is this doing? The square bracket syntax is used for returning a substring. This works like so: [<start>:<end>:<step>]. If […]

Reading environment variables in python

Posted: 13th November 2012 by Tim in Python
Tags: , , , , , ,

Shell envronment variables contain many useful paths and settings. At times you may want to use these variables from within a python program. This can be done via the os.path.expandvars(<var>) call, defined in os.path. For example, the following program: import os.path print os.path.expandvars(‘$SHELL’); Will print (on my machine): /bin/bash