[英]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.