Python Programming Cheat Sheet & Tips

Python Programming Cheat Sheet & Tips

Introduction to Python Tips & Tricks

On this page I capture all the little Python tips & tricks which I discover while working with Python. They tend to be the little snippets which are too small for a full blog post.

Don’t use Print for debugging

There is a good alternative to using Print in the Python Ice cream Library – see this great article for a full introduction.

For me, one of the key benefits is, it makes the intent clear. When you’ve finished debugging there is no doubt about what was temporary debug code and what should be kept. It’s much easier to search through for ‘ic’ and remove all those lines than it is for ‘print’.

Jupyter Keyboard Shortcuts

Key combinationJupyter Function
Alt-EnterInsert new row / cell
Shift-EnterRun cell

Use f Strings to format Dates and Times

import datetime
now =
print(f'{now:%Y-%m-%d %H:%M}')

Use this with the Python formatting codes below.

%aWeekday, short versionWed
%AWeekday, full versionWednesday
%wWeekday as a number 0-6, 0 is Sunday3
%dDay of month 01-3131
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mMonth as a number 01-1212
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2317
%IHour 00-125
%MMinute 00-5941
%SSecond 00-598
%fMicrosecond 000000-9999995E+05
%zUTC offset100
%jDay number of year 001-366365
%UWeek number of year, Sunday as the first day of week, 00-5352
%WWeek number of year, Monday as the first day of week, 00-5352
%cLocal version of date and timeMon Dec 31 17:41:00 2018
%xLocal version of date12/31/18
%XLocal version of time####
%%A % character%

It’s odd but there’s no built in method for nicely formatting a date with the ‘st’, ‘nd’, ‘rd’ or ‘th’ so I use this function

def fday(n):
    return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))

You can then do something like

print(f’Today is {now:%B} {fday(} {now:%Y}’)

and you will get a nicely formatted date like “July 24th 2021” which I like as a readable and globally unambiguous date, far better than 07242021 or 072421 or 240721….all of which you can work out when the day of the month is >12 but where the day of the month is <12 the reader doesn’t know how to interpret the date.


Recent Posts

Popular Posts

You May Also Like…

Find similar blogs in these categories: Python