Case Insensitive Python string split()方法

Yin*_*ang 13 python string

我有2个字符串

a = "abc feat. def"
b = "abc Feat. def"
Run Code Online (Sandbox Code Playgroud)

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

这就是我在做的事情,

a.split("feat.", 1)[0].rstrip()
Run Code Online (Sandbox Code Playgroud)

这回来了abc.但是如何使用拆分分隔符执行不区分大小写的搜索?

这是我到目前为止所尝试的

b.split("feat." or "Feat.", 1)[0].rstrip()
Run Code Online (Sandbox Code Playgroud)

输出 - 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

为什么与此不同and,并or在这两种情况下?

Tim*_*ker 16

改为使用正则表达式:

>>> 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']
Run Code Online (Sandbox Code Playgroud)

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

>>> regex = re.compile(r"\s*[Ff]eat\.\s*")
Run Code Online (Sandbox Code Playgroud)


Ble*_*ers 9

a[0:a.lower().find("feat.")].rstrip() 会做.

andING

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

返回最后一个字符串.

orING

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

会返回第一个字符串.

短路评估.