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 https://towardsdatascience.com/stop-using-print-to-debug-in-python-use-icecream-instead-79e17b963fcc 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 combination | Jupyter Function |
Alt-Enter | Insert new row / cell |
Shift-Enter | Run cell |
Use f Strings to format Dates and Times
import datetime now = datetime.datetime.now() print(f'{now:%Y-%m-%d %H:%M}')
Use this with the Python formatting codes below.
Directive | Description | Example |
%a | Weekday, short version | Wed |
%A | Weekday, full version | Wednesday |
%w | Weekday as a number 0-6, 0 is Sunday | 3 |
%d | Day of month 01-31 | 31 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month as a number 01-12 | 12 |
%y | Year, short version, without century | 18 |
%Y | Year, full version | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 00-12 | 5 |
%p | AM/PM | PM |
%M | Minute 00-59 | 41 |
%S | Second 00-59 | 8 |
%f | Microsecond 000000-999999 | 5E+05 |
%z | UTC offset | 100 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 365 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%x | Local version of date | 12/31/18 |
%X | Local 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.day)} {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.
0 Comments