0

I have the string x = "123+456-789" and I want to have the "123+456-" and "789" in separate variables. How can I store the last few characters of a string excluding the character "-" in a variable and store the rest in a different variable? This also has to work no matter how many "+" or "-" or other arithmetic operators are in the string (the last few digits excluding special characters have to be in a separate variable).

I have the last characters but I need the first few to be stored in a different variable:

>>> equation_text = "123+456-789"
>>> re.split(r"[+-/*%]", equation_text)[-1]
'789'

I used slicing:

>>> re.split(r"[+-/*%]", equation_text)[:-1]
['123', '456']

But the "+" and "-" are missing.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Is the separator always a `+`? – Pranav Hosangadi Feb 02 '23 at 19:44
  • No, the separator is not always a "+". – Canofeggs 5410 Feb 02 '23 at 19:45
  • https://stackoverflow.com/questions/15012228/splitting-on-last-delimiter-in-python-string – Pranav Hosangadi Feb 02 '23 at 19:46
  • 1
    Does this answer your question? [Split Strings into words with multiple word boundary delimiters](https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters) Since `re` doesn't have a `rsplit`, you could reverse the string, split as the link above shows, adding `maxsplit=1`, and reverse the resulting parts – Pranav Hosangadi Feb 02 '23 at 19:47
  • What are the other separators? Please update your question with a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Aleksa Majkic Feb 02 '23 at 19:47
  • @mkrieger1 I need to store the rest of the string. I have the last bit but if I try to store the first part (123+456+), it stores it without the last "+" – Canofeggs 5410 Feb 02 '23 at 19:55
  • You can find the last separator with `re.findall('\D', equation_text)[-1]` then use @PranavHosangadi's method. – Swifty Feb 02 '23 at 20:47
  • @mkrieger1 I want the other part of re.split to be in its seperate variable with all the seperators ("+","-","/"). Example: var = "123+456+789" -> var1 = "123+456+" var2 = "789". Sorry if my question wasn't clear, Im bad at explaining – Canofeggs 5410 Feb 03 '23 at 17:51
  • 1
    See https://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators. → `parts = re.split(r"([+-/*%])", equation_text)`, `var1 = ''.join(parts[:-1])`, `var2 = parts[-1]` – mkrieger1 Feb 03 '23 at 18:48

0 Answers0