用短横线替换空格并移除字符串前缀
我正在使用这个方法来去掉空格和特殊字符,并把字母转换成小写:
''.join(e for e in artistName if e.isalnum()).lower()
我想要:
把空格替换成
-
如果字符串以
the
开头,那么就要处理一下
比如说,The beatles music!
最后会变成 beatles-music
。
4 个回答
3
从 Python 3.9
开始,你可以使用 removeprefix
这个功能:
'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
# 'beatles-music'
3
听起来你想要制作一个机器可读的短链接。使用一个库来实现这个功能会让你省去很多麻烦。python-slugify 可以满足你的需求,还能做一些你可能没想到的其他事情。
24
artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。