0

我有一个字符串,它是我从 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"

所以我真正需要解决的问题是为什么我要用 'the'<SPACE>代替<NULL>. 但是,如果有人有更好的方法来做到这一点,我会为教育感到高兴:)

4

2 回答 2

8

使用

sArtist.replace('The','')

很危险。如果艺术家的名字是西奥多会怎样?

也许改用正则表达式:

In [11]: import re
In [13]: re.sub(r'^(?i)(a|an|the) (.*)',r'\2, \1','The Beatles')
Out[13]: 'Beatles, The'
于 2011-01-29T22:25:49.573 回答
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'
>>>
于 2011-01-29T22:28:06.500 回答