11

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.

4 Answers 4

25
artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
    artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')
Sign up to request clarification or add additional context in comments.

1 Comment

...startswith('the-') would be better; an artist may be named theodore ;-)
3

It sounds like you want to make a machine readable slug. Using a library for this function will save you lots of headache. python-slugify does what you are asking for and a bunch of other things you might not have even thought of.

Comments

3

Starting in Python 3.9, you can also use removeprefix:

'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
# 'beatles-music'

Comments

0

This would be best done with a bunch of regex-es so you can easily add to it over time.

Not sure of the python syntax but if it was perl you'd do something like:

s/^The //g;  #remove leading "The "
s/\s/-/g;    #replace whitespaces with dashes

It looks like python has a nice little howto for regexes: http://docs.python.org/howto/regex.html

1 Comment

An answer should have some code that works, especially with regexes b/c, since it varies so much from language to language. Not the regexes so much as the commands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.