-1

How can I split a string of tuples into a list?

For example I have this SARIMAX(0, 1, 1)x(0, 1, 1, 12) string, and I want to convert it into a list of tuples into this ['(0, 1, 1)', '(0, 1, 1, 12)']

This is my code:

sarimax_res = 'SARIMAX(0, 1, 1)x(0, 1, 1, 12)'
sarimax_res = sarimax_res.replace('SARIMAX', '').replace('x', '')

My output:

'(0, 1, 1)(0, 1, 1, 12)'
Mandera
  • 2,647
  • 3
  • 21
  • 26
MADFROST
  • 1,043
  • 2
  • 11
  • 29

3 Answers3

2
import re
from ast import literal_eval

sarimax_res = 'SARIMAX(0, 1, 1)x(0, 1, 1, 12)'
tuples = list(map(literal_eval, re.findall('\(.+?\)', sarimax_res)))
print(tuples)

# Output:
[(0, 1, 1), (0, 1, 1, 12)]

One-Liner for just strings:

re.findall('\(.+?\)', sarimax_res)

# Output:
['(0, 1, 1)', '(0, 1, 1, 12)']
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
  • Instead of splitting on `', '` in the second stage, it might be better to make it a regex search and split on `r',\s*'`; that depends on the data – Jiří Baum Sep 01 '22 at 03:41
  • Good to see the result! Thanks, it helps me, actually, I need the list of tuple strings. but anyway thanks!!! – MADFROST Sep 01 '22 at 03:42
  • @RudyTriSaputra added the string only method as well~ – BeRT2me Sep 01 '22 at 04:06
0

ast.literal_eval can safely evaluate the string.

We can use it by replacing the x with a comma, making literal_eval return a tuple of tuples, since you wanted list it's just cast to a list.

from ast import literal_eval

sarimax_res = 'SARIMAX(0, 1, 1)x(0, 1, 1, 12)'
sarimax_res = sarimax_res.replace('SARIMAX', '').replace("x", ",")
list(literal_eval(sarimax_res))

>>> [(0, 1, 1), (0, 1, 1, 12)]
Mandera
  • 2,647
  • 3
  • 21
  • 26
0

Since you wanted a list of string tuples you can just split the string on the x like this:

sarimax_res = 'SARIMAX(0, 1, 1)x(0, 1, 1, 12)'
sarimax_res.replace('SARIMAX', '').split("x")

>>> ['(0, 1, 1)', '(0, 1, 1, 12)']
Mandera
  • 2,647
  • 3
  • 21
  • 26