与re.split()相同的rsplit()是什么?

时间:2021-10-23 03:04:53

rsplit() starts splitting at the end of the string. How can I start splitting at the end of the string when using re.split()?

rsplit()在字符串的末尾开始拆分。使用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).

但这似乎不是最有效的方法,因为这会拆分整个字符串,而我们可以在第一场比赛后(从右边)停止。

1 个解决方案

#1


3  

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

如果您只想要最后一个,则无需拆分。

match = re.search(r'[^!?]*$', splitme)
if match:
    return match.group(0)

#1


3  

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

如果您只想要最后一个,则无需拆分。

match = re.search(r'[^!?]*$', splitme)
if match:
    return match.group(0)