0

I have a string like this:

'{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}'

I want to split this string and save them into a list like this using python:

 ['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']

When I do this :

r=re.split(r"['{}']", s)

But I receive this result, which is not what I want :

['', '"po": 118.0, "count": 1.0', ', ', '"po": 124.0, "count": 1.0', ', ', '"po": 132.0, "count": 2.0', '']

Would you please guide me on how to use a regular expression to split the string?

Any help is really appreciated.

2 Answers 2

1

This looks a lot like a fragment from some JSON content, and, if so, then you might want to work with the original valid JSON. If you must proceed at your current starting point, then I would suggest using re.findall here:

inp = '{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}'
output = re.findall(r'\{.*?\}', inp)
print(output)

This prints:

['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']

This approach should be fine assuming your input doesn't have any nested content.

Sign up to request clarification or add additional context in comments.

Comments

1

Would you please try the following:

import re

str = '{"po": 118.0, "count": 1.0}, {"po": 124.0, "count": 1.0}, {"po": 132.0, "count": 2.0}'
r = re.split(r'(?<=}),\s*(?={)', str)
print(r)

Output:

['{"po": 118.0, "count": 1.0}', '{"po": 124.0, "count": 1.0}', '{"po": 132.0, "count": 2.0}']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.