[英]Replace spaces with dash and remove prefix from string
我正在使用它来删除空格和特殊字符并将字符转换为小写:
''.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。 为这个 function 使用库将为您省去很多麻烦。 python-slugify 可以满足您的要求以及您可能没有想到的许多其他事情。
这最好用一堆正则表达式来完成,这样你就可以随着时间的推移轻松地添加它。
不确定 python 语法,但如果它是 perl 你会这样做:
s/^The //g; #remove leading "The "
s/\s/-/g; #replace whitespaces with dashes
看起来 python 有一个很好的正则表达式小方法: http://docs.python.org/howto/regex.ZDFC369FDC70D22786
从Python 3.9
开始,您还可以使用removeprefix
:
'The beatles music'.replace(' ', '-').lower().removeprefix('the-')
# 'beatles-music'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.