[英]Case Insensitive Python string split() method
我有2個字符串
a = "abc feat. def"
b = "abc Feat. def"
我想在feat.
這個詞之前檢索字符串feat.
或者Feat.
這就是我在做的事情,
a.split("feat.", 1)[0].rstrip()
這將返回abc
。 但是如何使用拆分分隔符執行不區分大小寫的搜索?
這是我到目前為止所嘗試的
b.split("feat." or "Feat.", 1)[0].rstrip()
輸出 - abc Feat. def
abc Feat. def
b.split("feat." and "Feat.", 1)[0].rstrip()
輸出 - abc
a.split("feat." and "Feat.", 1)[0].rstrip()
輸出 - abc feat. def
abc feat. def
。
a.split("feat." or "Feat.", 1)[0].rstrip()
輸出 - abc
為什么有這種差異and
和or
在兩種情況?
改為使用正則表達式:
>>> 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*")
a[0:a.lower().find("feat.")].rstrip()
會這樣做。
and
"string1" and "string2" and ... and "stringN"
返回最后一個字符串。
or
"string1" or "string2" or ... or "stringN"
會返回第一個字符串。
短路評估 。
你應該使用正則表達式:
re.split('\s*[Ff]eat\.', a)
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.