Radheya
Radheya

Reputation: 821

trouble extracting elements to list from string

I am using python and facing problem to extract specific elements from string which has tuples consisting of numbers. One thing to note here is tuples of numbers in the strings are not fixed, it can be more or less. The format of string will be same as mentioned below:

'string = [(100, 1), (2500, 2), (5000, 3), (10000, 3).....]'

Desired output:

[100,2500,5000,10000.....]

What I tried:

So far I tried splitting above string to get following output

['string', '=', '(100', '1)', '(2500', '2)', '(5000', '3)', '(10000, '3)']

and after that I was planning to strip unwanted characters like (,' to get numbers I want but this method has to be hard coded for every tuple and the length of tuples in string is not fixed.

Upvotes: 1

Views: 80

Answers (4)

Mayur Koshti
Mayur Koshti

Reputation: 1862

>>> s = 'string = [(100, 1), (2500, 2), (5000, 3), (10000, 3)]'
>>> l = [i[0] for i in eval(s.split("=")[1])]
>>> l
[100, 2500, 5000, 10000]

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19753

You can ast.literal_eval:

>>> import ast
>>> my_str = 'string = [(100, 1), (2500, 2), (5000, 3), (10000, 3)]'
>>> [x[0] for x in ast.literal_eval(my_str.split("=")[-1].strip())]
[100, 2500, 5000, 10000]

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

You can split your text with = to find the list of tuples then use ast.literaleval() to evaluate your list:

>>> next(zip(*literal_eval(s.split('=')[-1].strip())))
(100, 2500, 5000, 10000)

Note that since in python 2.X zip returns a list you can use indexing to get the first item:

zip(*literal_eval(s.split('=')[-1].strip()))[0]
(100, 2500, 5000, 10000)

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174786

Use re.findall

>>> s = 'string = [(100, 1), (2500, 2), (5000, 3), (10000, 3).....]'
>>> print [int(i) for i in re.findall(r'\((\d+)', s)]
[100, 2500, 5000, 10000]

Upvotes: 2

Related Questions