Home > Back-end >  "x.rsplit()" with multiple delimiters in Python
"x.rsplit()" with multiple delimiters in Python

Time:02-03

I have this code:

x.rsplit(" ", 1)[-1]

The string will be splitted at the end once if " " is in the way.

Example:

12 345 32 --> 32

But I want it to split if " ", "-" or "/" are in the way (Not just with " " but also with "-" or "/")

Example:

12 345 - 32 --> 32

or

12 345 / 32 --> 32

How can I add multiple limits when splitting?

CodePudding user response:

You can use a regex to split the string based on the operators and return the rightmost result:

re.split(r"[ -/]", x)[-1]

CodePudding user response:

Instead of splitting into a list you can extract the last "chunk" with precise regex matching:

import re

s = '12 345 - 32'
res = re.search(r'(?<=[ -/])[^ -/] $', s).group()
print(res)

32
  • Related