pynew
pynew

Reputation: 57

python convert str to list

How do i convert

'[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'

to a list of strings, eg.

   ['update', '/CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', 'Centaurus-AB']

Upvotes: 1

Views: 7797

Answers (4)

Richard
Richard

Reputation: 15862

strings = '[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'

strings = strings.replace("[", "").split(',')

print strings

EDIT:

oops. you want strip.. strip only takes first and last chars. Replace well remove all

strings = '[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'

strings = strings.strip("[]", "").split(',')

print strings

Upvotes: 4

tokland
tokland

Reputation: 67850

Without knowing more details about the input (do we really need to check if the brackets are there? commas are valid inside a field? ...) the simplest way probably is:

>>> [s.strip() for s in input_line[1:-1].split(',')]
['update', '/CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', 'Centaurus-AB']

Upvotes: 8

cledoux
cledoux

Reputation: 4947

There is probably a better way to do this, but the first way I think of is:

>>> y = '[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'
>>> y = y.split(',')
>>> y[0] = y[0].lstrip('[')
>>> y[-1] = y[-1].rstrip(']')
>>> y
['update', ' /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', ' Centaurus-AB']

Upvotes: 2

unutbu
unutbu

Reputation: 879411

In [12]: text='[update, /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1], Centaurus-AB]'
In [17]: text[1:-1].split(',')
Out[17]: ['update', ' /CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', ' Centaurus-AB']

Note that using text[1:-1] relies on the string starting and ending with brackets (or, at least, some throw-away character).

To get rid of the whitespace you could use strip():

In [18]: [elt.strip() for elt in text[1:-1].split(',')]
Out[18]: ['update', '/CoaddedRegriddedFrame[1]/OBJECT[1]/text()[1]', 'Centaurus-AB']

Upvotes: 2

Related Questions