簡體   English   中英

string.replace('the','')離開空白

[英]string.replace('the','') is leaving white space

我有一個字符串,它是我從MP3 ID3標簽獲得的藝術家的名字

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>替換'the'。 但是,如果有人有更好的方法可以做到這一點,我將為教育感到高興:)

使用

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'

單程:

>>> 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'
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM