rsplit()
starts splitting at the end of the string. How can I start splitting at the end of the string when using re.split()
?
Example:
import re
splitme = "a!b?c!d"
re.split(r"[!\?]", splitme, maxsplit = 1)
Returns:
a
But I want:
d
While I was writing this question, I realized I could use
re.split(r"[!\?]", splitme)[-1]
But that doesn’t seem like the most effective way since this splits the entire string, while we could stop after the first match (from the right).
The difference between split() and rsplit() is the use of the maxsplit argument. If the maxsplit argument is set, the rsplit() function splits a string from the right side (from the final character), whereas the split() method splits from the left side (from the first character).
The re. split() function splits the given string according to the occurrence of a particular character or pattern. Upon finding the pattern, this function returns the remaining characters from the string in a list.
With the re. split() method, you can specify a pattern for the delimiter, while with the defaults split() method, you could have used only a fixed character or set of characters. Also, using re. split() we can split a string by multiple delimiters.
There is no need to split if you just want the last one.
match = re.search(r'[^!?]*$', splitme)
if match:
return match.group(0)
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