2011-01-29 42 views
0

我有一個字符串,它是一個藝術家,我從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>更換。但是,如果有人有更好的方式來做到這一點,我將很高興爲教育:)

回答

2

方式一:

>>> def reformat(artist,beg): 
... if artist.startswith(beg): 
...  artist = artist[len(beg):] + ', ' + beg.strip() 
... return artist 
... 
>>> reformat('The Beatles','The ') 
'Beatles, The' 
>>> reformat('An Officer and a Gentleman','An ') 
'Officer and a Gentleman, An' 
>>> 
8

使用

sArtist.replace('The','') 

是危險的。如果藝術家的名字是Theodore,會發生什麼?

也許使用正則表達式來代替:

In [11]: import re 
In [13]: re.sub(r'^(?i)(a|an|the) (.*)',r'\2, \1','The Beatles') 
Out[13]: 'Beatles, The' 
+0

偉大的答案。這裏有一個小的改變,它可以很容易地擴展爲其他的忽略詞:re.sub(r'^((?i)a | the | an)(。*)',r'\ 2,\ 1', 'The Beatles') – 2011-01-29 22:30:27

+1

Regexp絕對是這裏的方式。不區分大小寫的標誌也可以解決第二個問題:`re.compile(r'^ The(。*)',re.I).sub(r'\ 1,the','The Beatles')` – ide 2011-01-29 22:30:58