10

I'm new to python and confused about converting a string to a list. I'm unsure how to create a list within a list to accomplish the following:

Ex.

string = '2,4,6,8|10,12,14,16|18,20,22,24' 

I'm trying to use split() to create a data structure, my_data, so that when I input

print my_data[1][2] #it should return 14

Stuck: This is what I did at first:

new_list = string.split('|')  #['2,4,6,8', '10,12,14,16,', '18,20,22,24']

And I know that you can't split a list so I split() the string first but I don't know how to convert the strings within the new list into a list in order to me to get the right output.

2
  • You can't .split a list but you can split the strings inside the list which is what I have done Commented Aug 10, 2012 at 5:10
  • +1 for such a well-written question! You actually tried to solve your problem, posted what you had tried, and then asked for specific help on where to go next - bravo! Commented Aug 10, 2012 at 7:29

2 Answers 2

23
>>> text = '2,4,6,8|10,12,14,16|18,20,22,24'
>>> my_data = [x.split(',') for x in text.split('|')]
>>> my_data
[['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']]
>>> print my_data[1][2]
14

Maybe you also want to convert each digit (still strings) to int, in which case I would do this:

>>> [[int(y) for y in x.split(',')] for x in text.split('|')]
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!! I like the first way you did this. I'm not looking to convert each digit to int but I see why one would do that.
2
>>> strs = '2,4,6,8|10,12,14,16|18,20,22,24'
>>> strs1=strs.split('|')
>>> [map(int,x.split(',')) for x in strs1] 
[[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]

Note: for python 3.x use list(map(int,x.split(','))), as map() returns a map object in python 3.x

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.