gpt4 book ai didi

python - 不区分大小写的 Python 字符串 split() 方法

转载 作者:太空狗 更新时间:2023-10-29 17:40:22 40 4
gpt4 key购买 nike

我有两个字符串

a = "abc feat. def"
b = "abc Feat. def"

我想检索单词 feat.Feat. 之前的字符串

这就是我在做的

a.split("feat.", 1)[0].rstrip()

这将返回 abc。但是如何使用分隔符执行不区分大小写的搜索?

这是我目前尝试过的

b.split("feat." or "Feat.", 1)[0].rstrip()

输出 - abc 壮举。 def

b.split("feat."and "Feat.", 1)[0].rstrip()

输出 - abc

a.split("feat."and "Feat.", 1)[0].rstrip()

输出 - abc feat. def.

a.split("feat."或 "Feat.", 1)[0].rstrip()

输出 - abc

为什么在这两种情况下 andor 会有这种差异?

最佳答案

改用正则表达式:

>>> import re
>>> regex = re.compile(r"\s*feat\.\s*", flags=re.I)
>>> regex.split("abc feat. def")
['abc', 'def']
>>> regex.split("abc Feat. def")
['abc', 'def']

或者,如果您不想允许 FEAT.fEAT.(此正则表达式会这样做):

>>> regex = re.compile(r"\s*[Ff]eat\.\s*")

关于python - 不区分大小写的 Python 字符串 split() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782186/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com