字符串。替换('the','')正在离开白色sp

2024-09-27 02:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,是一个艺术家的名字,我从mp3id3标签中得到

sArtist = "The Beatles"

我想把它换成

^{pr2}$

我遇到了两个不同的问题。我的第一个问题是,我似乎在用“The”来交换“”。在

if sArtist.lower().find('the') == 0:
    sArtist = sArtist.lower().replace('the','')
    sArtist = sArtist + ", the"

我的第二个问题是,因为我必须同时检查我使用的“The”和“The”萨蒂斯特。下(). 然而,这改变了我的成绩从“披头士,披头士”变成了“披头士,the”。为了解决这个问题,我删除了.lower并添加了第二行代码来显式地查找这两种情况。在

if sArtist.lower().find('the') == 0:
    sArtist = sArtist.replace('the','')
    sArtist = sArtist.replace('The','')
    sArtist = sArtist + ", the"

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


Tags: the字符串if标签find名字lowerreplace
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'
>>>

使用

sArtist.replace('The','')

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

或许可以使用regex代替:

^{pr2}$

相关问题 更多 >

    热门问题