Written by Sean Behan on Thu Mar 02nd 2017

There are a few 3rd party modules that do this sort of thing. But there is a pretty solution using out of the box Python functionality. You don't have to install any dependencies if you use the re module.

import re
text = ' asdfladf ljklasfj 2324@#$@#$@#43-----hi'
print re.sub(r'\W+', '-', text).strip('-')

Which will give you this pretty looking thing

asdfladf-ljklasfj-2324-43-hi

And keep in mind that the strip('-') will remove any preceding or trailing hyphens!


Tagged with..
#Python #Slugs #Re #Regex #Web Development

Just finishing up brewing up some fresh ground comments...