Case Insensitive Python string split()方法

时间:2013-12-26 09:16:53

标签: python string

我有2个字符串

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

我想在单词feat.Feat.

之前检索字符串

这就是我正在做的事,

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

返回abc。但是如何使用split delimiter执行不区分大小写的搜索?

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

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

在这两种情况下,为什么这与[{1}}和and存在差异?

3 个答案:

答案 0 :(得分:15)

改为使用正则表达式:

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

答案 1 :(得分:8)

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

and ING

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

返回最后一个字符串。

or ING

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

将返回第一个字符串。

Short-circuit evaluation

答案 2 :(得分: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."