Python字符串分割方法split()不区分大小写

14

我有2个字符串

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 Feat. def

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

输出 - abc

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

输出 - abc feat. def

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

输出 - abc

为什么在这两种情况下使用andor会有不同的结果?

3个回答

17

使用正则表达式替代:

>>> 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*")

10

a[0:a.lower().find("feat.")].rstrip()会起到作用。

and操作:

"string1" and "string2" and ... and "stringN"

返回最后一个字符串。

or操作:

"string1" or "string2" or ... or "stringN"

将返回第一个字符串。

短路求值


1

你应该使用正则表达式:

re.split('\s*[Ff]eat\.', a)

andor用于布尔逻辑判断。

"feat." or "Feat." -> "feat." if "feat." else "Feat." -> "feat."

"feat." and "Feat." -> "Feat." if "feat." else "feat." -> "Feat."

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接