I have 2 strings
a = "abc feat. def"
b = "abc Feat. def"
I want to retrieve the string before the word feat.
or Feat.
This is what I'm doing,
a.split("feat.", 1)[0].rstrip()
This returns 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
b.split("feat." and "Feat.", 1)[0].rstrip()
Output - abc
a.split("feat." and "Feat.", 1)[0].rstrip()
Output - abc feat. def
.
a.split("feat." or "Feat.", 1)[0].rstrip()
Output - abc
Why is this difference with and
and or
in both the cases?
Splitting string by mask is case-sensitive. So, be sure to type the characters in the mask exactly as they appear in the source strings.
Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.
The maxsplit parameter of re. split() is used to define how many splits you want to perform. In simple words, if the maxsplit is 2, then two splits will be done, and the remainder of the string is returned as the final element of the list.
If you want to split a string that matches a regular expression (regex) instead of perfect match, use the split() of the re module. In re. split() , specify the regex pattern in the first parameter and the target character string in the second parameter.
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.
or fEAT.
(which this regex would):
>>> regex = re.compile(r"\s*[Ff]eat\.\s*")
a[0:a.lower().find("feat.")].rstrip()
would do.
and
ing
"string1" and "string2" and ... and "stringN"
returns the the last string.
or
ing
"string1" or "string2" or ... or "stringN"
would return the first string.
Short-circuit evaluation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With