【问题标题】:string.replace('the','') is leaving white spacestring.replace('the','') 留下空白
【发布时间】:2011-01-29 22:18:04
【问题描述】:

我有一个字符串,它是我从 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”。但如果有人有更好的方法来做到这一点,我会为教育感到高兴:)

【问题讨论】:

    标签: python string mp3 id3


    【解决方案1】:

    使用

    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'
    

    【讨论】:

    • 很好的答案。这是一个小的更改,可以轻松地将其扩展为其他忽略词:re.sub(r'^((?i)a|the|an) (.*)',r'\2, \1', “披头士”)
    • Regexp 绝对是这里的必经之路。不区分大小写标志也可以解决第二个问题:re.compile(r'^The (.*)', re.I).sub(r'\1, the', 'The Beatles')
    • @Jason LeBrun 和 @ide:谢谢你们的建议。
    【解决方案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'
    >>>
    

    【讨论】:

    • 您找到了答案...我忘记了“The”后面的空格。我将它从“the”更改为“the”,这就是为什么我得到前面的 。我不知道 .startswith 选项。我会用它来代替。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2023-03-03
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多