Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace spaces with dash and remove prefix from string

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.

like image 852
user664546 Avatar asked May 02 '11 19:05

user664546


People also ask

How do you replace spaces with dashes?

Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.

How do you replace a space in a string?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do I remove spaces between words in a string Python?

Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


2 Answers

artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
    artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')
like image 129
Steve Howard Avatar answered Oct 20 '22 20:10

Steve Howard


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.

like image 45
Tristan Avatar answered Oct 20 '22 20:10

Tristan