Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the equivalent of rsplit() with re.split()?

Tags:

python

regex

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).

like image 565
doncherry Avatar asked Aug 15 '16 10:08

doncherry


People also ask

What is the difference between Rsplit and split?

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).

What is re split () in Python?

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.

What is the difference between re split and split in Python?

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.


1 Answers

There is no need to split if you just want the last one.

match = re.search(r'[^!?]*$', splitme)
if match:
    return match.group(0)
like image 170
tripleee Avatar answered Oct 14 '22 17:10

tripleee