string.replace('the','') 留下空白

发布于 2024-10-14 16:03:16 字数 782 浏览 6 评论 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”。但如果有人有更好的方法来做到这一点,我会很高兴接受教育:)

I have a string that is the name of an artist that I get from the MP3 ID3 tag

sArtist = "The Beatles"

What I want is to change it to

sArtist = "Beatles, the"

I have running into 2 different problems. My first problem is that I seem to be trading 'The' for ''.

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

My second problem is that since I have to check for both 'The' and 'the' I use sArtist.lower(). However this changes my result from " Beatles, the" to " beatles, the". To solve that problem I just removed the .lower and added a second line of code to explicitly look for both cases.

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

So the problem I really need to solve is why am I replacing 'the' with <SPACE> instead of <NULL>. But if somebody has a better way to do this I would be glad for the education :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

¢好甜 2024-10-21 16:03:16

使用

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'

Using

sArtist.replace('The','')

is dangerous. What happens if the artist's name is Theodore?

Perhaps use regex instead:

In [11]: import re
In [13]: re.sub(r'^(?i)(a|an|the) (.*)',r'\2, \1','The Beatles')
Out[13]: 'Beatles, The'
逆流 2024-10-21 16:03:16

单程:

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

One way:

>>> 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'
>>>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文