Akhil Unnikrishnan

A cheatsheet for the lazy Python developer

Python

Sharing a bunch of Python “quirks” that I keep revisiting. For some reason, I can never commit these to memory and have to resort to a quick search here and there. Compiled this list to help reduce the googling I have to do.

Keys in a Python dict

Keys are unique within a dictionary and cannot be duplicated or reused inside the same dictionary. If used more than once, subsequent entries will overwrite the previous value.

Removing elements from Python list and dict

Use list_name.remove(element_value) to remove element_value from list_name.

Use dict_object.pop(key_name) to remove that key and its value from the dictionary.

Replacing spaces with other characters in Python

To replace every occurrence of a space in a string with an underscore _, simply use the replace() function that’s available in the Python standard library.

my_string.replace(" ", "_")

Get a list of words from a string in Python

If you have a string with multiple words and want to get a list of those constituent words, simply use the split() method of the str class.

>>> search_term = "this string has multiple words"
>>> word_list = search_term.split()
>>> word_list
["this", "word", "has", "multiple", "words"]

Databases

A couple of database quirks I’ve found.

SQL Server

In SQL Server, the binary data type is defined as binary(n)

where n is a value from 1 through 8000, representing anything between 1 byte and 8000 bytes.

If you want to store an integer value (say, 123456) in binary, you will need 17 bits to store it in a SQL Server table. 17 bits is a bit over 16 bits (2 bytes), so the binary equivalent of 123456 gets rounded up to 3 bytes. Now if you try to store it in a 16 bit (2 byte) binary object, a silent truncation occurs, and the most significant bit is dropped. This changes the decimal equivalent from 123456 to 57920.

123,456 = b11110001001000000  
// Removing the last bit gives us b1110001001000000.  
b1110001001000000 = 57,920

This truncation is silent and occurs without raising any warnings or errors, so this is something you should look out for.

SQLite

SQLite does not print out column headers by default, possibly to reduce on-screen clutter. This behaviour can be changed and the table can me made prettier using

.headers on
.mode markdown

This enables the column headers, and formats the table in Markdown, so it’s easier to copy them into a Markdown file. You can replace Markdown mode with .mode column, but I’ve found Markdown mode produces consistently appealing tables.

#Python