I found the answer here.
Adding the following to my .vimrc file did the trick:
autocmd BufWritePre *.py :%s/\s\+$//e
The e
flag at the end means that the command doesn’t issue an error message if the search pattern fails. See :h :s_flags
for more.