简体   繁体   English

用破折号替换空格并从字符串中删除前缀

[英]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如果字符串以单词the开头,那么它

So that, for instance, The beatles music!例如, The beatles music! would become beatles-music .将成为beatles-music

artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
    artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')

It sounds like you want to make a machine readable slug.听起来你想制作一个机器可读的 slug。 Using a library for this function will save you lots of headache.为这个 function 使用库将为您省去很多麻烦。 python-slugify does what you are asking for and a bunch of other things you might not have even thought of. python-slugify 可以满足您的要求以及您可能没有想到的许多其他事情。

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:不确定 python 语法,但如果它是 perl 你会这样做:

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看起来 python 有一个很好的正则表达式小方法: http://docs.python.org/howto/regex.ZDFC369FDC70D22786

Starting in Python 3.9 , you can also use removeprefix :Python 3.9开始,您还可以使用removeprefix

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM