SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

How to Create a Slug in Python with the Re Module

       

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 w/ #python #slugs #re #regex #web development

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app