我有一個字符串,它是一個藝術家,我從MP3 ID3標籤獲得的名稱與string.replace(「的」,「」)離開空白
sArtist = "The Beatles"
我要的是改變它到
sArtist = "Beatles, the"
我遇到了2個不同的問題。我的第一個問題是我似乎在爲''交易'The'。
if sArtist.lower().find('the') == 0:
sArtist = sArtist.lower().replace('the','')
sArtist = sArtist + ", the"
我的第二個問題是因爲我必須檢查'The'和'the'我使用sArtist.lower()。然而,這改變了我的結果,從「披頭士樂隊」到「披頭士樂隊」。爲了解決這個問題,我剛剛刪除了.lower並添加了第二行代碼來明確查找這兩種情況。
if sArtist.lower().find('the') == 0:
sArtist = sArtist.replace('the','')
sArtist = sArtist.replace('The','')
sArtist = sArtist + ", the"
所以我真的需要解決的問題是,爲什麼我「的」與<SPACE>
而不是<NULL>
更換。但是,如果有人有更好的方式來做到這一點,我將很高興爲教育:)
偉大的答案。這裏有一個小的改變,它可以很容易地擴展爲其他的忽略詞:re.sub(r'^((?i)a | the | an)(。*)',r'\ 2,\ 1', 'The Beatles') – 2011-01-29 22:30:27
Regexp絕對是這裏的方式。不區分大小寫的標誌也可以解決第二個問題:`re.compile(r'^ The(。*)',re.I).sub(r'\ 1,the','The Beatles')` – ide 2011-01-29 22:30:58