Replace spaces with dash and remove prefix from string

user664546 picture user664546 · May 2, 2011 · Viewed 21.3k times · Source

I'm using this to remove spaces and special characters and convert characters to lowercase:

''.join(e for e in artistName if e.isalnum()).lower()

I want to:

  • replace spaces with -

  • if the string starts with the word the, then it

So that, for instance, The beatles music! would become beatles-music.

Answer

Steve Howard picture Steve Howard · May 2, 2011
artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
    artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')