Home > other >  Splitting a string of multiple bracketed values to a list of bracketed values in Python
Splitting a string of multiple bracketed values to a list of bracketed values in Python

Time:07-26

I would like to create a list of strings inside of brackets, given one long string of multiple bracketed values.

For instance, my string looks like this:

initial_string = '(1.5 0.1 0.3) (1.1 0.3 0.2) (1.9 0.6 0.4) (1.7 0.1 0.2)'

I would like it to become:

['(1.5 0.1 0.3)', '(1.1 0.3 0.2)', '(1.9 0.6 0.4)', '(1.7 0.1 0.2)']

I tried a few things, like re.split(' ', initial_string) but that splits the values inside the string as well.

How can I solve this problem?

CodePudding user response:

Using lookarounds to check for the parentheses:

import re

re.split(r'(?<=\))\s (?=\()', initial_string)

Output:

['(1.5 0.1 0.3)', '(1.1 0.3 0.2)', '(1.9 0.6 0.4)', '(1.7 0.1 0.2)']

Regex:

(?<=\)) # match (but do not consume) a ")"
\s      # match spaces
(?=\()  # match (but do not consume) a "("

CodePudding user response:

I would keep it simple and just use re.findall here:

initial_string = '(1.5 0.1 0.3) (1.1 0.3 0.2) (1.9 0.6 0.4) (1.7 0.1 0.2)'
matches = re.findall(r'\(.*?\)', initial_string)
print(matches)
# ['(1.5 0.1 0.3)', '(1.1 0.3 0.2)', '(1.9 0.6 0.4)', '(1.7 0.1 0.2)']

CodePudding user response:

Just use the .split() function and split on the space character

i.e

initial_string = '(1.5 0.1 0.3) (1.1 0.3 0.2) (1.9 0.6 0.4) (1.7 0.1 0.2)'
print(initial_string.split(' '))

This outputs

['(1.5', '0.1', '0.3)', '(1.1', '0.3', '0.2)', '(1.9', '0.6', '0.4)', '(1.7', '0.1', '0.2)']

  • Related