By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,870 Members | 2,484 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,870 IT Pros & Developers. It's quick & easy.

Extract tuples from space separated string of tuples.

P: 2
I have string in the following form:

Expand|Select|Wrap|Line Numbers
  1.  my_string = '(1, 2) (3, 4)'
As you can see, the tuples inside the string are space separated. I want to know how can I extract those tuples into separate variables.
Jun 16 '15 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
There may be a better way.
Expand|Select|Wrap|Line Numbers
  1. >>> my_string = '(1, 2) (3, 4)'
  2. >>> eval(my_string.replace(") (", "),("))
  3. ((1, 2), (3, 4))
  4. >>> a,b = eval(my_string.replace(") (", "),("))
  5. >>> a
  6. (1, 2)
  7. >>> b
  8. (3, 4)
  9. >>> 
Jun 16 '15 #2

P: 2
Thank you bvdet. But I have a question.

Can you please explain me what is happening in the code ?? I have never used eval function in Python.

Also I have read that using eval is not recommended in Python. Can you tell me why is that ??

EDIT: I used your approach of substituting the
Expand|Select|Wrap|Line Numbers
  1. ) (
part with
Expand|Select|Wrap|Line Numbers
  1. ), (
so that I get the string

Expand|Select|Wrap|Line Numbers
  1. (1, 2), (3, 4)
Then after that, I searched on StackOverflow about ast module and literal_eval function.

converting-string-to-tuple

I used it to separate the tuples into variables.

Thank You for the help .
Jun 16 '15 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Built-in funcation eval: Python documentation for eval

The function could potentially evaluate malicious code, therefore its use if sometimes frowned upon. A regex solution could potentially be a more robust but complicated solution.

Expand|Select|Wrap|Line Numbers
  1. >>> import re
  2. >>> re.compile("[(](\d+, \d+)[)]")
  3. <_sre.SRE_Pattern object at 0x0000000005C3EA80>
  4. >>> pattern = re.compile("[(](\d+, \d+)[)]")
  5. >>> pattern.findall('(1, 2) (3, 4)')
  6. ['1, 2', '3, 4']
  7. >>> ((int(i) for i in item.split(",")) for item in pattern.findall('(1, 2) (3, 4)'))
  8. <generator object <genexpr> at 0x0000000005E7CD38>
  9. >>> for obj in ((int(i) for i in item.split(",")) for item in pattern.findall('(1, 2) (3, 4)')):
  10. ...     print tuple(obj)
  11. ...     
  12. (1, 2)
  13. (3, 4)
  14. >>> 
Jun 16 '15 #4

Post your reply

Sign in to post your reply or Sign up for a free account.