我正在使用它来删除空格和特殊字符并将字符转换为小写:
''.join(e for e in artistName if e.isalnum()).lower()
我想要:
将空格替换为
-
如果字符串以单词开头
the
,那么它
因此,例如,The 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 == '-')
听起来你想制作一个机器可读的 slug。为这个函数使用一个库将为你省去很多麻烦。python-slugify 可以满足您的要求以及您可能没有想到的许多其他事情。
这最好用一堆正则表达式来完成,这样你就可以随着时间的推移轻松地添加它。
不确定 python 语法,但如果它是 perl 你会做类似的事情:
s/^The //g; #remove leading "The "
s/\s/-/g; #replace whitespaces with dashes
看起来 python 对正则表达式有一个很好的小方法:http: //docs.python.org/howto/regex.html
从 开始Python 3.9
,您还可以使用removeprefix
:
'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
# 'beatles-music'