Slugify a string in Python

Given a relatively complex string, such as an article title, it's often desirable to produce a hyphenated equivalent that works as a valid URL without requiring any special encoding.

For example, this wouldn't work as a valid URL at all:[Some] _ Article's Title--

... because it would have to be encoded like this:'s%20Title--

.. but "slugifying" the original title makes the result much more readable (and valid!):

This function can surely be simplified or improved (performance-wise) but I wrote it mostly for clarity.

This was inspired by a similar function in Django, but I didn't like the way that implementation handled certain sequences of characters (e.g. I believe it would return some-_-articles-title- for the input above).