9

我正在使用它来删除空格和特殊字符并将字符转换为小写:

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

我想要:

  • 将空格替换为-

  • 如果字符串以单词开头the,那么它

因此,例如,The beatles music!将变为beatles-music

4

4 回答 4

23
artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
    artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')
于 2011-05-02T19:17:35.757 回答
2

听起来你想制作一个机器可读的 slug。为这个函数使用一个库将为你省去很多麻烦。python-slugify 可以满足您的要求以及您可能没有想到的许多其他事情。

于 2016-01-14T11:32:31.843 回答
0

这最好用一堆正则表达式来完成,这样你就可以随着时间的推移轻松地添加它。

不确定 python 语法,但如果它是 perl 你会做类似的事情:

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

看起来 python 对正则表达式有一个很好的小方法:http: //docs.python.org/howto/regex.html

于 2011-05-02T19:19:26.707 回答
0

从 开始Python 3.9,您还可以使用removeprefix

'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
# 'beatles-music'
于 2020-04-25T21:08:11.630 回答