Python 用破折号替换空格,并从字符串中删除前缀
我使用它来删除空格和特殊字符,并将字符转换为小写:Python 用破折号替换空格,并从字符串中删除前缀,python,string,replace,prefix,Python,String,Replace,Prefix,我使用它来删除空格和特殊字符,并将字符转换为小写: ''.join(e for e in artistName if e.isalnum()).lower() 我想: 将空格替换为- 如果字符串以单词开头,则 例如,披头士乐队的音乐将变成披头士音乐这最好用一堆正则表达式来完成,这样你可以随着时间的推移轻松添加到其中 artistName = artistName.replace(' ', '-').lower() if artistName.startswith('the-'):
''.join(e for e in artistName if e.isalnum()).lower()
我想:
- 将空格替换为
-
- 如果字符串以单词
开头,则
例如,披头士乐队的音乐代码>将变成披头士音乐这最好用一堆正则表达式来完成,这样你可以随着时间的推移轻松添加到其中
artistName = artistName.replace(' ', '-').lower()
if artistName.startswith('the-'):
artistName = artistName[4:]
artistName = ''.join(e for e in artistName if e.isalnum() or e == '-')
不确定python语法,但如果是perl,您可以执行以下操作:
s/^The //g; #remove leading "The "
s/\s/-/g; #replace whitespaces with dashes
看起来python对正则表达式有一个很好的小说明:听起来你想制作一个机器可读的slug。为这个函数使用一个库会让你省去很多麻烦。做你想做的事情和一些你可能没有想到的事情。从
Python 3.9开始,你还可以使用:
…用('the-')启动将更好;一位艺术家可以叫西奥多;-)答案应该有一些代码,特别是正则表达式b/c,因为不同语言的代码差别很大。与其说是正则表达式,不如说是命令。
'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
# 'beatles-music'