1

How to split a string variable like below into individual groups? var.split(",") splits those inside the brackets also.

var = "(5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg')"

desired result:

[(5, 'kghjsg'),  
(6, 'kghjsghk'), 
..
] 
1
  • Is your string guaranteed to be in that format? If so, you can use literal_eval(). Commented Jan 14, 2014 at 21:20

1 Answer 1

4

Use ast.literal_eval:

>>> from ast import literal_eval
>>> var = "(5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg')"
>>> literal_eval(var)
((5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg'))

From docs:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

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

1 Comment

Note this assumes the string to be parsed is a valid Python expression.

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.