[英]Case Insensitive Python string split() method
I have 2 strings 我有2个字符串
a = "abc feat. def"
b = "abc Feat. def"
I want to retrieve the string before the word feat.
我想在
feat.
这个词之前检索字符串feat.
or Feat.
或者
Feat.
This is what I'm doing, 这就是我在做的事情,
a.split("feat.", 1)[0].rstrip()
This returns abc
. 这将返回
abc
。 But how can I perform a case insensitive search using split delimiter? 但是如何使用拆分分隔符执行不区分大小写的搜索?
This is what I've tried so far 这是我到目前为止所尝试的
b.split("feat." or "Feat.", 1)[0].rstrip()
Output - abc Feat. def
输出 -
abc Feat. def
abc Feat. def
b.split("feat." and "Feat.", 1)[0].rstrip()
Output - abc
输出 -
abc
a.split("feat." and "Feat.", 1)[0].rstrip()
Output - abc feat. def
输出 -
abc feat. def
abc feat. def
. abc feat. def
。
a.split("feat." or "Feat.", 1)[0].rstrip()
Output - abc
输出 -
abc
Why is this difference with and
and or
in both the cases? 为什么有这种差异
and
和or
在两种情况?
Use a regex instead: 改为使用正则表达式:
>>> 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']
or, if you don't want to allow FEAT.
或者,如果你不想允许
FEAT.
or fEAT.
或者
fEAT.
(which this regex would): (这是正则表达式):
>>> regex = re.compile(r"\s*[Ff]eat\.\s*")
a[0:a.lower().find("feat.")].rstrip()
would do. a[0:a.lower().find("feat.")].rstrip()
会这样做。
and
ing and
"string1" and "string2" and ... and "stringN"
returns the the last string. 返回最后一个字符串。
or
ing or
"string1" or "string2" or ... or "stringN"
would return the first string. 会返回第一个字符串。
You should use regex: 你应该使用正则表达式:
re.split('\s*[Ff]eat\.', a)
and
and or
do some boolean judgement. and
or
做一些布尔判断。
"feat." or "Feat." -> "feat." if "feat." else "Feat." -> "feat."
"feat." and "Feat." -> "Feat." if "feat." else "feat." -> "Feat."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.