Python slugify function
I often need to transform a string to something usable in a URL. Over the years I’ve used this snippet a bunch to do just that:
(nb: “slug” is a a newspaper term that is much used throughout Django, the web framework I cut my teeth on. As a concept, it maps very nicely to URLs).
The thing I like most about this snippet is 2/3 of the function body is about removing characters instead of adding/replacing them.
Like if the input string already has a dash, it removes it before going any further.
If, after the first line, there is one or more dashes in a row, it collapses them into a single dash.
This all results in a very clean output.