Python Cheat Sheet

I like to solve my problems in python, so here is a small cheat sheet on python tricks that make my life easier.

There’s not much yet, but more to come!

End for loop on return-key hit

If you need a certain task done over and over again, you can use watch -n [seconds] 'task', but I sometimes need all the information at once without a clear page after every execution. That’s where python comes in handy.

import sys, select

print "Hit <Return> to exit"
while True:
	print "I'm doing stuff :)"
	if sys.stdin in[sys.stdin], [], [], 0)[0]:
        print "Exiting..."

This little snippet will do what you want until the end of (up)time – or until you hit the return button.

HTTP requests made easy

Normally Python uses urllib to make HTTP request, but that’s kind of a PITA and not very pythonic. “requests” is a library that aims to make it easier – and it does!

Everything you need to know to get started can be found here

It’s easy to install

git clone git://
cd folder
sudo python install

and easy to use

>>> r = requests.get('', auth=('user', 'pass'))
>>> r.status_code
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
>>> r.text
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

Manipulating strings

There is one thing that baffled me when it comes to strings in python.
Namely, I wanted to print the two middle characters of a string. This is how it’s done

	# My string (I want to print "CD")
	>>> string = "ABCDEF"
    # get half the length of the string (string == 6, half ==3)
    >>> pos = len(string)/2
    # print the middle chars.
    >>> print string[pos:pos+1]

Note: pos == 3, pos+1 == 4
To my understanding, pos and pos+1 shoudl print character 3 and 4, meaning CD. Python however sees positions as pointers to the chars meaning pos+1 points to the beginning of the 4th char. Therefore the 4th character D is not printed. To get both, you need to specify the start of the 5th character, as this is also the end of the 4th.

The correct syntax to print CD would be

>>> print string[pos:pos+2]

For more string manipulation, look here.