Home > Back-end >  Split a string containing multiple tuples into list of string tuples
Split a string containing multiple tuples into list of string tuples

Time:09-01

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

CodePudding user response:

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)']

CodePudding user response:

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

CodePudding user response:

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)']
  • Related